text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Drawing; using System.IO; using System.Net.Http; using System.Text; using System.Windows.Forms; using UseFul.ClientApi; using UseFul.ClientApi.Dtos; using UseFul.Forms.Welic; using UseFul.Uteis; using UseFul.Uteis.UI; using Welic.WinForm.Properties; namespace Welic.WinForm.Cadastros.Estacionamento { public partial class frmSolicitacoesVagas : FormCadastro { //public frmSolicitacoesVagas() //{ // InitializeComponent(); // //Inicialização dos Eventos. // this.Load += new EventHandler(LoadFormulario); // this.toolStripBtnNovo.Visible = true; // this.toolStripBtnNovo.Click += new EventHandler(ClickNovo); // this.toolStripBtnEditar.Visible = true; // this.toolStripBtnEditar.Click += new EventHandler(ClickEditar); // this.toolStripBtnExcluir.Visible = true; // this.toolStripBtnExcluir.Click += new EventHandler(ClickExcluir); // this.toolStripBtnGravar.Visible = true; // this.toolStripBtnGravar.Click += new EventHandler(ClickGravar); // this.toolStripBtnVoltar.Visible = true; // this.toolStripBtnVoltar.Click += new EventHandler(ClickVoltar); // this.toolStripBtnLocalizar.Visible = true; // this.toolStripBtnLocalizar.Click += new EventHandler(ClickLocalizar); // this.toolStripBtnImprimir.Visible = true; // this.toolStripBtnImprimir.Click += new EventHandler(ClickImprimir); // this.toolStripBtnAuditoria.Visible = false; // this.toolStripBtnAjuda.Visible = false; // this.toolStripSeparatorAcoes.Visible = true; // this.toolStripSeparatorOutros.Visible = false; // this.KeyUp += new KeyEventHandler(KeyUpFechar); // InserirBotaoToolStrip(); //} //public frmSolicitacoesVagas(string solicitacao) //{ // InitializeComponent(); // //Inicialização dos Eventos. // this.Load += new EventHandler(LoadFormulario); // this.toolStripBtnNovo.Visible = true; // this.toolStripBtnNovo.Click += new EventHandler(ClickNovo); // this.toolStripBtnEditar.Visible = true; // this.toolStripBtnEditar.Click += new EventHandler(ClickEditar); // this.toolStripBtnExcluir.Visible = true; // this.toolStripBtnExcluir.Click += new EventHandler(ClickExcluir); // this.toolStripBtnGravar.Visible = true; // this.toolStripBtnGravar.Click += new EventHandler(ClickGravar); // this.toolStripBtnVoltar.Visible = true; // this.toolStripBtnVoltar.Click += new EventHandler(ClickVoltar); // this.toolStripBtnLocalizar.Visible = false; // this.toolStripBtnImprimir.Visible = true; // this.toolStripBtnImprimir.Click += new EventHandler(ClickImprimir); // this.toolStripBtnAuditoria.Visible = false; // this.toolStripBtnAjuda.Visible = false; // this.toolStripSeparatorAcoes.Visible = true; // this.toolStripSeparatorOutros.Visible = false; // this.KeyUp += new KeyEventHandler(KeyUpFechar); // InserirBotaoToolStrip(); // this.solicitacao = solicitacao; //} //bool veiculoBicileta; //bool usuCartaoEstacionamento = false; //string veiculo = string.Empty; //public string solicitacao; //private void FormBuscaRegistros(object sender, bool filtraDadosInformados) //{ // FormBuscaPaginacao fb; // if (!filtraDadosInformados) // { // HttpResponseMessage response = // ClienteApi.Instance.RequisicaoGet("solicitacoes/get"); // var retorno = // ClienteApi.Instance.ObterResposta<List<SolicitacoesVagasDto>>(response); // if (retorno.Count > 0 ) // { // fb = new FormBuscaPaginacao(); // fb.SetListAsync<SolicitacoesVagasDto>(retorno, "IdSolicitacao"); // fb.ShowDialog(); // BindingSolicitacao.DataSource = fb.RetornoList<SolicitacoesVagasDto>(); // HttpResponseMessage responseVeic = // ClienteApi.Instance.RequisicaoGet($"Veiculo/get/{fb.RetornoList<SolicitacoesVagasDto>().IdVeiculo}"); // var retornoVeic = // ClienteApi.Instance.ObterResposta<VeiculoDto>(response); // if (retornoVeic != null) // { // BindingSolicitacao.DataSource = retornoVeic; // } // HttpResponseMessage responsePes = // ClienteApi.Instance.RequisicaoGet($"Veiculo/getByPessoa/{retornoVeic.IdPessoa}"); // var retornoPes = // ClienteApi.Instance.ObterResposta<VeiculoDto>(response); // } // } // else // LimpaCampos(); //} //// Inserir o método InserirBotaoToolStrip() no método construtor do formulário //private void InserirBotaoToolStrip() //{ // ToolStripButton botao = new ToolStripButton(); // // Deverá receber a localização do arquivo da Imagem // botao.Image = Resources.ICancel30x30; // botao.ImageAlign = ContentAlignment.MiddleCenter; // botao.ImageScaling = ToolStripItemImageScaling.None; // botao.Text = ""; // botao.AutoSize = true; // botao.Height = botao.Image.Height; // botao.Width = botao.Image.Width; // botao.ToolTipText = "Cancelar Solicitação"; // // Localização do Botão no ToolStrip // botao.Alignment = ToolStripItemAlignment.Right; // // Adicionando o botão ao ToolStrip // toolStripOpcoes.Items.Add(botao); // // Deverá receber o método a ser executado no Evento Click do novo botão // botao.Click += new EventHandler(btnBotaoCancelar_Click); //} //private void btnBotaoCancelar_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(txtSolicitacao.Text)) // MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser cancelado.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); // else if (lblSituacao.Text.Equals("CANCELADA")) // MessageBox.Show("A Solicitação já está cancelada!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // if (MessageBox.Show("Confirma o CANCELAMENTO da Solicitação " + txtSolicitacao.Text + "?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // try // { // HttpResponseMessage // response = ClienteApi.Instance.RequisicaoPost($"Solicitacoes/cancel/{txtSolicitacao.Text}"); // var retorno = // ClienteApi.Instance.ObterResposta<SolicitacoesVagasDto>(response); // MensagemStatusBar("Cancelado com sucesso."); // LiberaChaveBloqueiaCampos(this.Controls); // LimpaCampos(); // AcaoFormulario = CAcaoFormulario.Excluir; // } // catch (CustomException ex) // { // ProcessMessage(ex.Message, MessageType.Error); // } // catch (Exception exception) // { // ProcessException(exception); // } // } // } //} //private void PreencherFormulario() //{ // // Se a pesquisa retornar mais de uma Solicitação para os dados informados será exibido um FormBusca (metodo FormBuscaRegistros) // // com os resultados. // // Quando o usuário selecionar uma Solicitação este método será chamado novamente com todos os 4 filtros preenchidos, // // retornando apenas 1 registro em dt e, com isso, o formulário será preenchido // if (!this.Disposing) // { // HttpResponseMessage response = // ClienteApi.Instance.RequisicaoGet($"solicitacoes/getbyid/{txtSolicitacao.Text}"); // var retorno = // ClienteApi.Instance.ObterResposta<SolicitacoesVagasDto>(response); // if (retorno != null) // { // BindingSolicitacao.DataSource = retorno; // HttpResponseMessage responseVeic = // ClienteApi.Instance.RequisicaoGet($"Veiculo/get/{retorno.IdVeiculo}"); // var retornoVeic = // ClienteApi.Instance.ObterResposta<VeiculoDto>(response); // BindingVeiculo.DataSource = retornoVeic; // } // else // { // MessageBox.Show("Não foram encontradas Solicitações de Vaga para os dados informados.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // LimpaCampos(); // AcaoFormulario = CAcaoFormulario.Nenhum; // GerenciaCampos(); // } // if (!mtxtDataCancel.Text.Equals(" / /") || lblSituacao.Text.Equals("ATENDIDA")) // GerenciaToolStripMenu(true); // else // GerenciaToolStripMenu(false); // } //} //private void PreencherSituacao(int situacao, string dt_inicio) //{ // switch (situacao) // { // case 1: // lblSituacao.Text = "PENDENTE"; // break; // case 2: // lblSituacao.Text = "ATENDIDA"; // break; // case 3: // lblSituacao.Text = "CANCELADA"; // break; // default: // lblSituacao.Text = ""; // break; // } // mtxtInicio.Text = dt_inicio; //} //private void PreencherEstacionamentosIndicados() //{ // if (!string.IsNullOrEmpty(txtSolicitacao.Text)) // { // if (dgvEstacionamentosIndicados.DataSource != null) // ((DataTable)dgvEstacionamentosIndicados.DataSource).Clear(); // string manha = "0"; // string tarde = "0"; // string noite = "0"; // if (dgvContratos.DataSource != null) // { // DataTable dtPeriodos = ((DataTable)dgvContratos.DataSource); // manha = (dtPeriodos.Select("MANHA = 1").Length > 0 ? "1" : "0"); // tarde = (dtPeriodos.Select("TARDE = 1").Length > 0 ? "1" : "0"); // noite = (dtPeriodos.Select("NOITE = 1").Length > 0 ? "1" : "0"); // } // dgvEstacionamentosIndicados.DataSource = // new IndicacaoEstacionamento().BuscaIndicacaoEstacionamento(int.Parse(txtSolicitacao.Text)); // } //} //private void PreencherVeiculo() //{ // HttpResponseMessage response = // ClienteApi.Instance.RequisicaoGet($"pessoa/getbycpf/{mtxtCPF.Text.Replace('-',' ').Replace('.',' ')}"); // var retorno = // ClienteApi.Instance.ObterResposta<PessoaDto>(response); // HttpResponseMessage responseVeic = // ClienteApi.Instance.RequisicaoGet($"Veiculo/getByPessoa/{retorno.IdPessoa}"); // var retornoVeic = // ClienteApi.Instance.ObterResposta<VeiculoDto>(response); // BindingVeiculo.DataSource = retornoVeic; //} //private void PreencherContratos() //{ // //if (!string.IsNullOrEmpty(mtxtCPF.Text) && !this.Disposing) // //{ // // //Contratos de Técnico Administrativo // // DataTable dtContratosTecAdm = WBll.BuscaContratosColaboradorTecAdm(long.Parse(mtxtCPF.Text)); // // //Horários de Contrato de Docente // // DataTable dtHorariosDocente = WBll.BuscaHorariosColaboradorDocente(long.Parse(mtxtCPF.Text)); // // DataTable dt = new DataTable(); // // if (dtContratosTecAdm != null && dtContratosTecAdm.Rows.Count > 0) // // dt = dtContratosTecAdm.Copy(); // // if (dt.Rows.Count == 0) // // foreach (DataGridViewColumn coluna in dgvContratos.Columns) // // if (!string.IsNullOrEmpty(coluna.DataPropertyName)) // // dt.Columns.Add(coluna.DataPropertyName, typeof(string)); // // if (dtHorariosDocente != null && dtHorariosDocente.Rows.Count > 0) // // { // // DataRow dr = dt.NewRow(); // // dr["MANHA"] = "0"; // // dr["TARDE"] = "0"; // // dr["NOITE"] = "0"; // // DateTime inicio; // // DateTime termino; // // bool contemHorarioForaLimites = false; // // foreach (DataRow linha in dtHorariosDocente.Rows) // // { // // inicio = DateTime.Parse(linha["HORARIO_INICIO"].ToString()); // // termino = DateTime.Parse(linha["HORARIO_TERMINO"].ToString()); // // if (inicio.Hour >= 6 && inicio.Hour < 12) // // dr["MANHA"] = "1"; // // else if (inicio.Hour >= 14 && inicio.Hour < 18) // // dr["TARDE"] = "1"; // // else if (inicio.Hour >= 19 || inicio.Hour < 6) // // dr["NOITE"] = "1"; // // else // // contemHorarioForaLimites = true; // // } // // if(contemHorarioForaLimites) // // foreach (DataRow linha in dtHorariosDocente.Rows) // // { // // inicio = DateTime.Parse(linha["HORARIO_INICIO"].ToString()); // // termino = DateTime.Parse(linha["HORARIO_TERMINO"].ToString()); // // if (inicio.Hour >= 12 && inicio.Hour < 14) // // if (dr["TARDE"].ToString().Equals("0")) // // dr["MANHA"] = "1"; // // if (inicio.Hour >= 18 && inicio.Hour < 19) // // if (dr["NOITE"].ToString().Equals("0")) // // dr["TARDE"] = "1"; // // } // // dr["MATRICULA"] = dtHorariosDocente.Rows[0]["DOCENTE"].ToString(); // // dr["CATEGORIA"] = dtHorariosDocente.Rows[0]["CATEGORIA"].ToString(); // // dr["TIPO_CONTRATO"] = dtHorariosDocente.Rows[0]["TIPO_CONTRATO"].ToString(); // // dr["TIPCON"] = dtHorariosDocente.Rows[0]["TIPCON"].ToString(); // // dr["CH_MENSAL"] = dtHorariosDocente.Rows[0]["CH_MENSAL"].ToString(); // // dr["CAMPUS"] = dtHorariosDocente.Rows[0]["CAMPUS"].ToString(); // // dr["CAMPUS_DESC"] = dtHorariosDocente.Rows[0]["DESC_CAMPUS"].ToString(); // // dr["BLOCO"] = DBNull.Value; //dtHorariosDocente.Rows[0]["BLOCO"].ToString(); // // dr["BLOCO_DESC"] = ""; //dtHorariosDocente.Rows[0]["DESC_BLOCO"].ToString(); // // dr["CENTRO_CUSTO"] = dtHorariosDocente.Rows[0]["CENTRO_CUSTO"].ToString(); // // dr["CENTRO_CUSTO_DESC"] = dtHorariosDocente.Rows[0]["CENTRO_CUSTO_DESC"].ToString(); // // dt.Rows.Add(dr); // // } // // dgvContratos.DataSource = dt; // // // Buscar o registro do campo TELEFONE_VIGILANCIA da tabela mtd.colaboradores_cadastro // // if(dt.Rows.Count > 0) // // txtContatos.Text = WBll.BuscaTelefonesVigilanciaColaborador(dt.Rows[0]["MATRICULA"].ToString()); // //} // //else if (dgvContratos.DataSource != null) // // ((DataTable)dgvContratos.DataSource).Clear(); //} //private void GerenciaToolStripMenu(bool desativaEditarExcluir) //{ // if (desativaEditarExcluir) // CANCELADA // toolStripBtnExcluir.Enabled = false; // else // { // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // toolStripBtnExcluir.Enabled = true; // } //} //private void GerenciaCampos() //{ // if (AcaoFormulario == CAcaoFormulario.Editar || AcaoFormulario == CAcaoFormulario.Novo) // { // pnlContratos.Enabled = true; // pnlEstacionamentosIndicados.Enabled = true; // btnVeiculos.Enabled = true; // btnLiberarVaga.Enabled = true; // grpCNH.Enabled = true; // LiberaCabecalho(true); // } // else // { // pnlContratos.Enabled = false; // pnlEstacionamentosIndicados.Enabled = false; // btnVeiculos.Enabled = false; // btnLiberarVaga.Enabled = false; // grpCNH.Enabled = false; // LiberaCabecalho(true); // } //} //private void LiberaCabecalho(bool libera) //{ // mtxtCPF.Enabled = libera; // mtxtPlaca.Enabled = libera; // mtxtData.Enabled = libera; // txtColaborador.Enabled = libera; // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // txtSolicitacao.Enabled = false; // else // txtSolicitacao.Enabled = true; //} //private void LiberarCamposEdicaoVagaLiberada() //{ // grpCNH.Enabled = true; //} //private void LimpaCampos() //{ // LimpaCampos(this.Controls); // PreencherSituacao(0, ""); // GerenciaToolStripMenu(false); //} //private bool ValidaMaisDeUmaVagaMesmoEstacionamento() //{ // List<string> listaEstacionamentos = new List<string>(); // foreach (DataGridViewRow linha in dgvEstacionamentosIndicados.Rows) // { // if (listaEstacionamentos.Contains(linha.Cells["colEstacionamento"].Value.ToString())) // return false; // else // listaEstacionamentos.Add(linha.Cells["colEstacionamento"].Value.ToString()); // } // return true; //} //private void LiberarVaga(int solicitacao) //{ // try { // //Inicio da transação // long chave1; // foreach (DataGridViewRow linha in dgvEstacionamentosIndicados.Rows) // { // #region Cria registros de Solicitações de Vagas Liberadas // var solicitacoesVagasLiberadas = new SolicitacoesVagasLiberadasDto // { // Vaga = linha.Index, // IdEstacionamento = int.Parse(linha.Cells["colEstacionamento"].Value.ToString()), // IdVeiculo = int.Parse(mtxtPlaca.Tag.ToString()), // Manha = int.Parse(linha.Cells["colEstacionamentoManha"].Value.ToString()), // Tarde = int.Parse(linha.Cells["colEstacionamentoTarde"].Value.ToString()), // Noite = int.Parse(linha.Cells["colEstacionamentoNoite"].Value.ToString()), // IdUser = Globals.IdUser, // DtLiberacao = DateTime.Now, // DtValidade = DateTime.Parse(mskDataValidade.Text), // Situacao = 1, // TipoIdentificacao = 1 //TODO: Criar padrão como 1 // }; // HttpResponseMessage // response = ClienteApi.Instance.RequisicaoPost("Solicitacoes/saveVagasLiberadas", solicitacoesVagasLiberadas); // solicitacoesVagasLiberadas = // ClienteApi.Instance.ObterResposta<SolicitacoesVagasLiberadasDto>(response); // #endregion // #region Atualiza campos Vaga e Situação das Solicitações de Estacionamentos (tabela de estacionamentos indicados da solicitação) // chave1 = long.Parse(linha.Cells["colEstacionamento"].Value.ToString()); // HttpResponseMessage responseSolicEstacionamentoGet = // ClienteApi.Instance.RequisicaoGet($"Solicitacoes/GetSolicitacoesEstacionamentoByEstacionamento/{chave1}/{solicitacao}"); // var solicitacoesEstacionamento = // ClienteApi.Instance.ObterResposta<SolicitacoesEstacionamentoDto>(responseSolicEstacionamentoGet); // solicitacoesEstacionamento.Situacao = 2; // solicitacoesEstacionamento.Vaga = solicitacoesVagasLiberadas.Vaga; // HttpResponseMessage // responsePostEstacionamento = ClienteApi.Instance.RequisicaoPost("Solicitacoes/SaveEstacionamento", solicitacoesEstacionamento); // solicitacoesEstacionamento = // ClienteApi.Instance.ObterResposta<SolicitacoesEstacionamentoDto>(responsePostEstacionamento); // #endregion // } // #region Atualiza situação Solicitação de Vaga // HttpResponseMessage responseSolicVagasGet = // ClienteApi.Instance.RequisicaoGet($"Solicitacoes/GetById/{solicitacao}"); // var solicitacoesVagas = // ClienteApi.Instance.ObterResposta<SolicitacoesVagasDto>(responseSolicVagasGet); // solicitacoesVagas.Situacao = 2; // Situação 2 - Atendida // solicitacoesVagas.DtInicio = DateTime.Now; // #endregion // //Fim da transãção // PreencherFormulario(); // } // catch (CustomException ex) // { // ProcessMessage(ex.Message, MessageType.Error); // } // catch (Exception exception) // { // ProcessException(exception); // } //} //private void GerarDeclaracaoExterna() //{ // try // { // if (MessageBox.Show("Deseja imprimir a Declaração de Acesso ao Estacionamento B.V?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // string caminho = @"C:\sistemas\declaracao_externa.docx"; // string matricula = (dgvContratos.DataSource == null ? "---" : dgvContratos.Rows[0].Cells["colMatricula"].Value.ToString()); // WBll.GerarAutorizacaoVagaEstacionamento(txtCPFNome.Text, matricula, mtxtCPF.Text, caminho, mtxtPlaca.Text, null, 2, null, null, null, null, false); // System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(caminho); // info.Verb = "PrintTo"; // info.Arguments = System.Printing.LocalPrintServer.GetDefaultPrintQueue().FullName; // info.CreateNoWindow = true; // info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; // System.Diagnostics.Process.Start(info); // } // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "" + "\nErro: " + ex.InnerException.Message, "Erro - Declaração Externa", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "" + "\nErro: " + ex.Message, "Erro - Declaração Externa", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} //private DataTable FormataDataTableSugestaoEstac(DataTable dt) //{ // DataColumn coluna; // if (!dt.Columns.Contains("SITUACAO")) // { // coluna = new DataColumn("SITUACAO", typeof(string)); // coluna.DefaultValue = "1"; // dt.Columns.Add(coluna); // } // if (!dt.Columns.Contains("SITUACAO_DESC")) // { // coluna = new DataColumn("SITUACAO_DESC", typeof(string)); // coluna.DefaultValue = "PENDENTE"; // dt.Columns.Add(coluna); // } // if (!dt.Columns.Contains("SOLICITACAO")) // { // coluna = new DataColumn("SOLICITACAO", typeof(string)); // dt.Columns.Add(coluna); // } // if (!dt.Columns.Contains("VAGA")) // { // coluna = new DataColumn("VAGA", typeof(string)); // dt.Columns.Add(coluna); // } // return dt; //} //private DataTable BuscaEstacionamentosSugeridos() //{ // DataTable dtPeriodos = ((DataTable)dgvContratos.DataSource); // string manha = (dtPeriodos.Select("MANHA = 1").Length > 0 ? "1" : "0"); // string tarde = (dtPeriodos.Select("TARDE = 1").Length > 0 ? "1" : "0"); // string noite = (dtPeriodos.Select("NOITE = 1").Length > 0 ? "1" : "0"); // string tipo_veiculo = WBll.BuscaTipoVeiculo(mtxtPlaca.Text); // DataTable dtEstacionamentos = new DataTable(); // DataTable dtHorariosDocente = WBll.BuscaHorariosColaboradorDocente(long.Parse(mtxtCPF.Text)); // if (WBll.VerificaDocenteExclusivoEAD(mtxtCPF.Text)) // docente é exclusivo do EAD // { // dtEstacionamentos = WBll.BuscaEstacAtendemExclusivosEAD(null, tipo_veiculo); // if (dtEstacionamentos.Rows.Count == 0) // nao existe estacionamento cadastrado para atender EAD (mtd.estacionamentos.atende_exclusivos_ead) // { // string msg = "O Colaborador é um Docente exclusivo da Educação a Distância e "; // msg += "atualmente não existem Estacionamentos cadastrados para atender esta situação."; // msg += "\nPara fazer o cadastro vá até o Cadastro de Estacionamentos e marque o campo \"Atende docentes exclusivos da EAD\"."; // MessageBox.Show(this, msg, "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // return dtEstacionamentos; // } // else // retorna os estacionamentos que atendem docentes exclusivos do EAD // { // return FormataDataTableSugestaoEstac(dtEstacionamentos); // } // } // else if (dtHorariosDocente.Rows.Count > 0) // { // // INICIO - Pesquisa Estacionamentos que atendam especificamente aos cursos em que o Docente ministra aulas // List<DataRow> listaCursos = new List<DataRow>(); // // Busca todos os cursos em que o docente ministra aulas // foreach (DataRow linha in dtHorariosDocente.Rows) // if (!listaCursos.Contains(linha) && !string.IsNullOrEmpty(linha["CURSO"].ToString()) && !string.IsNullOrEmpty(linha["CAMPUS"].ToString())) // listaCursos.Add(linha); // // estacionamentos que atendem a algum dos cursos que o docente ministra aulas // dtEstacionamentos = WBll.BuscaEstacionamentosAtendemCursos(listaCursos, tipo_veiculo, manha, tarde, noite); // if (dtEstacionamentos.Rows.Count > 0) // return FormataDataTableSugestaoEstac(dtEstacionamentos); // // FIM - Pesquisa Estacionamentos que atendam especificamente aos cursos em que o Docente ministra aulas // // INICIO - Pesquisa Estacionamentos que atendam ao Bloco em que o Docente mais ministra aulas // DataTable dtBlocoCampusMaiorCHoraria = WBll.BuscaBlocoCampusMaiorCargaHorariaDocente(mtxtCPF.Text); // if (dtBlocoCampusMaiorCHoraria.Rows.Count == 1) // { // dtEstacionamentos = WBll.BuscaEstacionamentosAtendemBloco(dtBlocoCampusMaiorCHoraria.Rows[0]["BLOCO"].ToString(), dtBlocoCampusMaiorCHoraria.Rows[0]["CAMPUS"].ToString(), tipo_veiculo, manha, tarde, noite); // if (dtEstacionamentos.Rows.Count > 0) // return FormataDataTableSugestaoEstac(dtEstacionamentos); // } // // FIM - Pesquisa Estacionamentos que atendam ao Bloco em que o Docente mais ministra aulas // } // MessageBox.Show("Não existem Estacionamentos com Vagas Disponíveis que atendam às necessidades do Colaborador.", "Titulo", MessageBoxButtons.OK, MessageBoxIcon.Information); // return dtEstacionamentos; //} //private void SugerirEstacionamentosDocente() //{ // DataTable dt = BuscaEstacionamentosSugeridos(); // if(dt != null && dt.Rows.Count > 0) // dgvEstacionamentosIndicados.DataSource = dt; //} //private void SugerirEstacionamentosTecADM(string campus, string tipo_veiculo) //{ // DataTable dtPeriodos = ((DataTable)dgvContratos.DataSource); // string manha = (dtPeriodos.Select("MANHA = 1").Length > 0? "1":"0"); // string tarde = (dtPeriodos.Select("TARDE = 1").Length > 0? "1":"0"); // string noite = (dtPeriodos.Select("NOITE = 1").Length > 0? "1":"0"); // DataTable dt = WBll.BuscaEstacionamentosComVagasAdministrativas(campus, tipo_veiculo, manha, tarde, noite); // DataColumn coluna = new DataColumn("SOLICITACAO", typeof(string)); // dt.Columns.Add(coluna); // dgvEstacionamentosIndicados.DataSource = dt; // if(dt.Rows.Count == 0) // MessageBox.Show("Não existem Estacionamentos que atendam as necessidades do Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); //} //private void SugerirEstacionamentosBicicletas() //{ // DataTable dtPeriodos = ((DataTable)dgvContratos.DataSource); // string manha, tarde, noite; // if (!usuCartaoEstacionamento) // { // manha = (dtPeriodos.Select("MANHA = 1").Length > 0 ? "1" : "0"); // tarde = (dtPeriodos.Select("TARDE = 1").Length > 0 ? "1" : "0"); // noite = (dtPeriodos.Select("NOITE = 1").Length > 0 ? "1" : "0"); // } // else // { // manha = "0"; // tarde = "0"; // noite = "0"; // } // DataTable dt = WBll.BuscaEstacionamentosComVagasBicicletas(manha, tarde, noite); // DataColumn coluna = new DataColumn("SOLICITACAO", typeof(string)); // dt.Columns.Add(coluna); // dgvEstacionamentosIndicados.DataSource = dt; // if (dt.Rows.Count == 0) // MessageBox.Show("Não existem Estacionamentos que atendam as necessidades do Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); //} ///// <summary> ///// Código Padrão - Load do Formulário - Tela de Cadastro ///// Versão 0.1 - 13/08/2010 ///// </summary> //private void LoadFormulario(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(this.solicitacao)) // { // LiberaChaveBloqueiaCampos(this.Controls); // LimpaCampos(); // ModoOpcoes(); // AcaoFormulario = CAcaoFormulario.Nenhum; // GerenciaCampos(); // } // else // { // txtSolicitacao.Text = this.solicitacao; // txtSolicitacao_Leave(null, null); // } //} ///// <summary> ///// Código Padrão - Ação Botão Novo - Tela de Cadastro ///// Versão 0.1 - 13/08/2010 ///// </summary> //private void ClickNovo(object sender, EventArgs e) //{ // LimpaCamposBloqueiaAutoIncremento(this.Controls); // mtxtData.Text = Globals.Sysdate.ToShortDateString(); // PreencherSituacao(0, ""); // ModoGravacao(); // AcaoFormulario = CAcaoFormulario.Novo; // txtColaborador.Enabled = true; // txtColaborador.TipoCampo = TextBoxWelic.CTipoCampo.Chave; // usuCartaoEstacionamento = false; // GerenciaCampos(); // txtColaborador.Focus(); //} ///// <summary> ///// Código Padrão - Ação Botão Editar - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void ClickEditar(object sender, EventArgs e) //{ // if (!mtxtDataCancel.Text.Equals(" / /") || lblSituacao.Text.Equals("ATENDIDA")) // { // BloqueiaChaveLiberaCampos(this.Controls); // LiberarCamposEdicaoVagaLiberada(); // ModoGravacao(); // AcaoFormulario = CAcaoFormulario.Editar; // } // else // { // if (!ValidaCamposObrigatorios(this.Controls)) // MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser alterado.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // BloqueiaChaveLiberaCampos(this.Controls); // ModoGravacao(); // AcaoFormulario = CAcaoFormulario.Editar; // GerenciaCampos(); // TratarCamposUsuCartaoEstacionamento(); // } // } //} ///// <summary> ///// Código Padrão - Ação Botão Excluir - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void ClickExcluir(object sender, EventArgs e) //{ // if (!ValidaCamposObrigatorios(this.Controls)) // MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser excluído.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // if (MessageBox.Show("Confirma a EXCLUSÃO da Solicitação " + txtSolicitacao.Text + "?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // try // { // using (EntitiesPrefeituraUniversitaria mde = new EntitiesPrefeituraUniversitaria(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString())) // { // //Declara e busca Entidade pela chave // int chave = int.Parse(txtSolicitacao.Text); // SOLICITACOES_VAGAS solicitacao = mde.SOLICITACOES_VAGAS.FirstOrDefault(x => x.SOLICITACAO == chave); // if (solicitacao == null) // throw new Exception("Registro não encontrado!"); // //Deleta Objeto ec.DeleteObject(instancia); // mde.DeleteObject(solicitacao); // //SaveChanges() (Commit) // mde.SaveChanges(); // MensagemStatusBar("Excluído com sucesso."); // LiberaChaveBloqueiaCampos(this.Controls); // LimpaCampos(); // AcaoFormulario = CAcaoFormulario.Excluir; // } // GerenciaCampos(); // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "Não foi possível excluir o registro." + "\nErro: " + ex.InnerException.Message, "Erro - Excluir", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Não foi possível excluir o registro." + "\nErro: " + ex.Message, "Erro - Excluir", MessageBoxButtons.OK, MessageBoxIcon.Error); // } // } // } //} ///// <summary> ///// Código Padrão - Ação Botão Gravar - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void ClickGravar(object sender, EventArgs e) //{ // if (!ValidaCamposObrigatorios(this.Controls)) // MessageBox.Show("Por favor, preencha os campos que identificam o registro.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); // else if (!ValidaMaisDeUmaVagaMesmoEstacionamento()) // MessageBox.Show("Não é possível salvar mais de 1 vaga para um mesmo Estacionamento.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // DbTransaction Transaction = null; // string mensagem = string.Empty; // using (EntityConnection DbConnection = new EntityConnection(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString())) // { // try // { // int chave; // string msg = ""; // if (DbConnection.State == ConnectionState.Closed) // DbConnection.Open(); //Abrindo Conexão // var CurrentContext = new EntitiesPrefeituraUniversitaria(DbConnection); //Passando como parametro o estado da Conexão // Transaction = CurrentContext.Connection.BeginTransaction(); //Iniciando a Transação // //Inicio da transação // #region Gravar registro Solicitação de Vaga // // Declaração da Entidade // SOLICITACOES_VAGAS solicitacao; // if (AcaoFormulario == CAcaoFormulario.Novo) // { // //Instância da Entidade // solicitacao = new SOLICITACOES_VAGAS(); // //Seta campos // solicitacao.CPF = mtxtCPF.Text; // solicitacao.VEICULO = int.Parse(mtxtPlaca.Tag.ToString()); // solicitacao.DT_SOLICITACAO = DateTime.Parse(mtxtData.Text); // solicitacao.USUARIO = Globals.Usuario; // solicitacao.SITUACAO = 1; // solicitacao.OBSERVACAO = txtObservacao.Text; // //Insere Registro // CurrentContext.AddToSOLICITACOES_VAGAS(solicitacao); // //SaveChanges() (Commit) // CurrentContext.SaveChanges(); // //Busca Chave AutoNumeracao // txtSolicitacao.Text = CurrentContext.SOLICITACOES_VAGAS.Max(x => x.SOLICITACAO).ToString(); // msg = "Salvo com sucesso."; // } // else if (AcaoFormulario == CAcaoFormulario.Editar) // { // //Busca Entidade pelas chaves // chave = int.Parse(txtSolicitacao.Text); // solicitacao = CurrentContext.SOLICITACOES_VAGAS.FirstOrDefault(x => x.SOLICITACAO == chave); // if (solicitacao == null) // throw new Exception("Registro não encontrado!"); // //Seta campos // solicitacao.CPF = mtxtCPF.Text; // solicitacao.VEICULO = int.Parse(mtxtPlaca.Tag.ToString()); // solicitacao.DT_SOLICITACAO = DateTime.Parse(mtxtData.Text); // solicitacao.OBSERVACAO = txtObservacao.Text; // //SaveChanges() (Commit) // CurrentContext.SaveChanges(); // msg = "Alterado com sucesso."; // } // #endregion // #region Atualiza Campos CNH do Colaborador e Campo TELEFONE_VIGILANCIA da tabela colaboradores_cadastro // if (!usuCartaoEstacionamento) // { // R034CPL vet; // foreach (DataGridViewRow linha in dgvContratos.Rows) // { // chave = int.Parse(linha.Cells["colMatricula"].Value.ToString()); // vet = CurrentContext.R034CPL.FirstOrDefault(x => x.NUMCAD == chave); // string cnh = string.Empty; // DateTime dataCnh = new DateTime(); // DateTime dataVenCnh = new DateTime(); // string atualizarCampos = string.Empty; // if (vet == null) // throw new Exception("Erro ao atualizar CNH."); // if (txtCNHNumero.Text.Length < 11) // cnh = txtCNHNumero.Text.PadLeft(11, '0'); // else // cnh = txtCNHNumero.Text; // if (!mtxtCNHData.Text.Equals(" / /")) // { // dataCnh = DateTime.Parse(mtxtCNHData.Text); // atualizarCampos += " ,c.datcnh = trunc(to_date('" + dataCnh + @"', 'dd/mm/yyyy hh24:mi:ss')) "; // } // else // atualizarCampos += " ,c.datcnh = null "; // if (!mtxtCNHVencimento.Text.Equals(" / /")) // { // dataVenCnh = DateTime.Parse(mtxtCNHVencimento.Text); // atualizarCampos += " ,c.vencnh = trunc(to_date('" + dataVenCnh + "', 'dd/mm/yyyy hh24:mi:ss')) "; // } // else // atualizarCampos += " ,c.vencnh = null "; // Conexao dal = new Conexao(Globals.GetStringConnection(), 2); // StringBuilder sql = new StringBuilder(); // sql.Append(@"update vetorh.r034cpl c set c.numcnh = '" + cnh + "' " + atualizarCampos + ", c.catcnh = '" + txtCNHCategoria.Text + "' where c.numcad = " + chave); // dal.ExecuteNonQuery(sql.ToString()); // if (Globals.Usuario != 16272) // { // mensagem = "Telefone Contato"; // sql.Clear(); // sql.Append("call bhora.up_r034fun_telvig(" + txtColaborador.Text + ", '" + txtContatos.Text + "')"); // dal.ExecuteNonQuery(sql.ToString()); // } // } // } // else // { // EntitiesPrefeituraUniversitaria mde = new EntitiesPrefeituraUniversitaria(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString()); // long chave3 = long.Parse(mtxtCPF.Text); // CARTOES_ESTACIONAMENTOS cartao = mde.CARTOES_ESTACIONAMENTOS.FirstOrDefault(x => x.CPF == chave3); // //Seta campos // cartao.NOME = txtCPFNome.Text; // cartao.CONTATO = txtContatos.Text; // cartao.OBSERVACAO = txtObservacao.Text; // mde.SaveChanges(); // } // #endregion // if (AcaoFormulario == CAcaoFormulario.Novo) // { // PreencherSituacao(1, ""); // txtSolicitacao.Text = CurrentContext.SOLICITACOES_VAGAS.Max(x => x.SOLICITACAO).ToString(); // } // #region grava indicações de vagas // SOLICITACOES_ESTACIONAMENTOS estacionamento; // long solic = long.Parse(txtSolicitacao.Text); // int estac; // bool novo; // foreach (DataGridViewRow linha in dgvEstacionamentosIndicados.Rows) // { // if(AcaoFormulario == CAcaoFormulario.Novo) // { // estacionamento = new SOLICITACOES_ESTACIONAMENTOS(); // estacionamento.SOLICITACAO = long.Parse(txtSolicitacao.Text); // estacionamento.ESTACIONAMENTO = int.Parse(linha.Cells["colEstacionamento"].Value.ToString()); // estacionamento.TIPO_VAGA = int.Parse(linha.Cells["colTipoVaga"].Value.ToString()); // estacionamento.MANHA = int.Parse(linha.Cells["colEstacionamentoManha"].Value.ToString()); // estacionamento.TARDE = int.Parse(linha.Cells["colEstacionamentoTarde"].Value.ToString()); // estacionamento.NOITE = int.Parse(linha.Cells["colEstacionamentoNoite"].Value.ToString()); // estacionamento.SITUACAO = 1; // CurrentContext.AddToSOLICITACOES_ESTACIONAMENTOS(estacionamento); // CurrentContext.SaveChanges(); // } // else if(AcaoFormulario == CAcaoFormulario.Editar) // { // estac = int.Parse(linha.Cells["colEstacionamento"].Value.ToString()); // estacionamento = CurrentContext.SOLICITACOES_ESTACIONAMENTOS.FirstOrDefault(x => x.SOLICITACAO == solic && // x.ESTACIONAMENTO == estac); // if (estacionamento == null) // { // estacionamento = new SOLICITACOES_ESTACIONAMENTOS(); // novo = true; // } // else // novo = false; // estacionamento.SOLICITACAO = long.Parse(txtSolicitacao.Text); // estacionamento.ESTACIONAMENTO = int.Parse(linha.Cells["colEstacionamento"].Value.ToString()); // estacionamento.TIPO_VAGA = int.Parse(linha.Cells["colTipoVaga"].Value.ToString()); // estacionamento.MANHA = int.Parse(linha.Cells["colEstacionamentoManha"].Value.ToString()); // estacionamento.TARDE = int.Parse(linha.Cells["colEstacionamentoTarde"].Value.ToString()); // estacionamento.NOITE = int.Parse(linha.Cells["colEstacionamentoNoite"].Value.ToString()); // estacionamento.SITUACAO = int.Parse(linha.Cells["colSituacao"].Value.ToString()); // if (novo) // CurrentContext.AddToSOLICITACOES_ESTACIONAMENTOS(estacionamento); // CurrentContext.SaveChanges(); // } // } // #endregion // //Fim da transãção // Transaction.Commit(); // MensagemInsertUpdate(msg); // } // catch (Exception ex) // { // Transaction.Rollback(); // if (ex.InnerException != null) // MessageBox.Show(this, "Ocorreu um erro ao gravar o registro.\n" + mensagem + "\nErro: " + ex.InnerException.Message, "Erro - Gravar", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Ocorreu um erro ao gravar o registro.\n" + mensagem + "\nErro: " + ex.Message, "Erro - Gravar", MessageBoxButtons.OK, MessageBoxIcon.Error); // throw ex; // } // finally // { // if (DbConnection != null) // if (DbConnection.State == ConnectionState.Open) // DbConnection.Close(); //Fechando Conexão // } // } // } //} //private void MensagemInsertUpdate(string mensagem) //{ // AcaoFormulario = CAcaoFormulario.Gravar; // ModoOpcoes(); // GerenciaCampos(); // MensagemStatusBar(mensagem); //} ///// <summary> ///// Código Padrão - Ação Botão Voltar - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void ClickVoltar(object sender, EventArgs e) //{ // LiberaChaveBloqueiaCampos(this.Controls); // LimpaCampos(); // ModoOpcoes(); // AcaoFormulario = CAcaoFormulario.Voltar; // txtColaborador.Enabled = true; // txtColaborador.TipoCampo = TextBoxWelic.CTipoCampo.Chave; // usuCartaoEstacionamento = false; // GerenciaCampos(); //} ///// <summary> ///// Código Padrão - Ação KeyUp Fechar(Esc) - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void KeyUpFechar(object sender, KeyEventArgs e) //{ // if (e.KeyCode == Keys.Escape) // { // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // LoadFormulario(sender, new EventArgs()); // else // this.Close(); // } //} ///// <summary> ///// Código Padrão - Ação Botão Imprimir - Tela de Cadastro ///// Versão 0.1 - 23/08/2010 ///// </summary> //private void ClickImprimir(object sender, EventArgs e) //{ // AcaoFormulario = CAcaoFormulario.Imprimir; // if (dgvContratos.Rows.Count == 0 && !usuCartaoEstacionamento) // MessageBox.Show("Colaborador Não possui contrato para gerar a Declaração!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // try // { // if (dgvEstacionamentosIndicados.Rows.Count == 0) // MessageBox.Show("Nenhum estacionamento indicado para gerar a Declaração!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // foreach (DataRow linha in ((DataTable)dgvEstacionamentosIndicados.DataSource).Rows) // { // string emissao = WBll.VerificaEmissaoDeclaracaoEstacionamento(linha["ESTACIONAMENTO"].ToString()).ToString(); // if (!string.IsNullOrEmpty(emissao)) // { // if (!veiculoBicileta)//Sugestão para vagas de carros e motos // { // switch (emissao) // { // case "3": // BELA VISTA PARKING // GerarDeclaracaoExterna(); // break; // case "2": // Estacionamentos Internos (blocos) // GerarDeclaracaoInterna(linha); // break; // default: // if (sender != null) // MessageBox.Show("O Estacionamento " + linha["ESTACIONAMENTO_DESC"].ToString() + " não emite declarações!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // break; // } // } // else // { // GerarDeclaracaoBicicleta(linha, veiculoBicileta); // } // } // } // } // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "Ocorreu um erro ao gerar uma Declaração de Acesso a Estacionamentos. Contate o Administrador do Sistema para verificar o problema" + "\nErro: " + ex.InnerException.Message, "Erro - Impressão", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Ocorreu um erro ao gerar uma Declaração de Acesso a Estacionamentos. Contate o Administrador do Sistema para verificar o problema" + "\nErro: " + ex.Message, "Erro - Impressão", MessageBoxButtons.OK, MessageBoxIcon.Error); // } // } //} //private void ClickLocalizar(object sender, EventArgs e) //{ // AcaoFormulario = CAcaoFormulario.Buscar; // txtSolicitacao_KeyDown(txtSolicitacao, new KeyEventArgs(Keys.F3)); //} //private void mtxtCPF_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtCPF.Text) && AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); // else if (string.IsNullOrEmpty(mtxtCPF.Text)) // { // txtCPFNome.Text = ""; // txtColaborador.Text = ""; // mtxtPlaca.Text = ""; // if (dgvContratos.DataSource != null) // ((DataTable)dgvContratos.DataSource).Clear(); // } //} //private void txtColaborador_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(txtColaborador.Text) && AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); // else if (string.IsNullOrEmpty(txtColaborador.Text)) // { // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // mtxtPlaca.Text = ""; // if (dgvContratos.DataSource != null) // ((DataTable)dgvContratos.DataSource).Clear(); // } //} //private void mtxtPlaca_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); // else // { // if (dgvEstacionamentosIndicados.DataSource != null) // ((DataTable)dgvEstacionamentosIndicados.DataSource).Clear(); // } // } //} //private void txtSolicitacao_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(txtSolicitacao.Text)) // LimpaCampos(); //} //private void mtxtData_TextChanged(object sender, EventArgs e) //{ // if (mtxtData.Text.Equals(" / /") && AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); //} //private void mtxtCPF_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtCPF.Text)) // mtxtCPF.SelectionStart = 0; //} //private void mtxtData_Click(object sender, EventArgs e) //{ // if (mtxtData.Text.Equals(" / /")) // mtxtData.SelectionStart = 0; //} //private void mtxtPlaca_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // mtxtPlaca.SelectionStart = 0; //} //private void mtxtCNHData_Click(object sender, EventArgs e) //{ // if (mtxtCNHData.Text.Equals(" / /")) // mtxtCNHData.SelectionStart = 0; //} //private void mtxtCNHVencimento_Click(object sender, EventArgs e) //{ // if (mtxtCNHVencimento.Text.Equals(" / /")) // mtxtCNHVencimento.SelectionStart = 0; //} //private void mtxtCPF_KeyDown(object sender, KeyEventArgs e) //{ // if (e.KeyCode == Keys.F3) // { // if (AcaoFormulario != CAcaoFormulario.Novo) // FormBuscaRegistros(sender, false); // else // Ação = Novo // { // FormBusca fb = new FormBusca(WBll.QueryBuscaColaboradorPorCPF("").ToString(), new List<System.Data.OracleClient.OracleParameter>(), true, "COLABORADORES", "NOME", txtCPFNome.Text, "Nenhum registro encontrado!", false, "NOME"); // fb.ShowDialog(); // if (fb.retorno != null) // { // mtxtCPF.Text = fb.retorno["CPF"].ToString(); // txtColaborador.Text = fb.retorno["matricula"].ToString(); // mtxtPlaca.Focus(); // } // } // } //} //private void mtxtCPF_Leave(object sender, EventArgs e) //{ // if (!string.IsNullOrEmpty(mtxtCPF.Text)) // { // // Se o formulário estiver na Ação Novo, trará apenas o nome, dados de CNH e Contratos do colaborador // // Se não irá procurar uma Solicitação para o CPF informado. // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // { // DataTable dt = WBll.BuscaColaboradorPorCPF(mtxtCPF.Text); // bool UsuarioOk = true; // //Caso o cpf não seja de colaborador, verifica se é de usuario de cartao de estacionamento // if (dt.Rows.Count == 0) // { // dt = WBll.BuscaUsuarioCartaoEstacionamento(mtxtCPF.Text); // if (dt.Rows.Count > 0) // { // usuCartaoEstacionamento = true; // txtObservacao.Text = dt.Rows[0]["OBSERVACAO"].ToString(); // txtContatos.Text = dt.Rows[0]["CONTATO"].ToString(); // txtColaborador.Enabled = false; // txtColaborador.TipoCampo = TextBoxWelic.CTipoCampo.Normal; // } // else if (AcaoFormulario == CAcaoFormulario.Novo) // { // //se não for usuario de cartao de estacionamento, busca na tabela de alunos // dt = WBll.BuscaAluno(mtxtCPF.Text); // if (dt.Rows.Count > 0) // { // if (MessageBox.Show("Aluno não cadastrado como usuário de cartão de estacionamento.\nDeseja cadastra-lo??", Globals.TituloSistema, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) // { // try // { // using (EntitiesPrefeituraUniversitaria mde = new EntitiesPrefeituraUniversitaria(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString())) // { // // Declaração da Entidade // CARTOES_ESTACIONAMENTOS cartao; // //Instância da Entidade // cartao = new CARTOES_ESTACIONAMENTOS(); // //Seta campos // cartao.CPF = long.Parse(mtxtCPF.Text); // cartao.NOME = dt.Rows[0]["nome"].ToString(); // cartao.CONTATO = dt.Rows[0]["contato"].ToString(); // //Insere Registro // mde.CARTOES_ESTACIONAMENTOS.AddObject(cartao); // //SaveChanges() (Commit) // mde.SaveChanges(); // txtCPFNome.Text = dt.Rows[0]["nome"].ToString(); // txtContatos.Text = dt.Rows[0]["contato"].ToString(); // usuCartaoEstacionamento = true; // txtColaborador.Enabled = false; // mtxtPlaca.Focus(); // } // } // catch (Exception ex) // { // MessageBox.Show("Erro ao inserir o usuário de cartão de estacionamento.\nErro: " + ex.Message, "Erro - Buscar CPF", MessageBoxButtons.OK, MessageBoxIcon.Error); // LimpaCampos(mtxtCPF); // mtxtCPF.Focus(); // return; // } // } // else // { // LimpaCampos(mtxtCPF); // mtxtCPF.Focus(); // return; // } // } // } // } // else // { // txtColaborador.Enabled = true; // txtColaborador.TipoCampo = TextBoxWelic.CTipoCampo.Chave; // } // TratarCamposUsuCartaoEstacionamento(); // if (dt.Rows.Count > 0) // { // txtCPFNome.Text = dt.Rows[0]["NOME"].ToString(); // if (!usuCartaoEstacionamento) // { // txtColaborador.Text = dt.Rows[0]["MATRICULA"].ToString(); // DataTable dtCargoLocal = WBll.BuscaCargoLocal(txtColaborador.Text); // if (dtCargoLocal.Rows.Count > 0) // { // txtCargo.Text = dtCargoLocal.Rows[0]["ds_cargo"].ToString(); // txtLocal.Text = dtCargoLocal.Rows[0]["ds_local"].ToString(); // } // if (!ValidaColabRecebeValeTransp(txtColaborador.Text)) // { // txtColaborador.Text = ""; // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // mtxtCPF.Focus(); // UsuarioOk = false; // } // else if (WBll.VerificaExisteSolicitacoesPendentes(mtxtCPF.Text)) // { // MessageBox.Show("Existem solicitações pendentes para o colaborador. Verifique antes de continuar.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // txtColaborador.Text = ""; // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // mtxtCPF.Focus(); // UsuarioOk = false; // } // } // if(UsuarioOk || usuCartaoEstacionamento) // { // // Buscar veículos do colaborador // DataTable dtVeiculo = WBll.BuscaVeiculosColaboradores(mtxtCPF.Text, 3, null); // if (dtVeiculo.Rows.Count > 0) // { // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // if (dtVeiculo.Rows.Count == 1) // { // mtxtPlaca.Text = dtVeiculo.Rows[0]["PLACA"].ToString(); // mtxtPlaca_Leave(null, null); // } // else // { // if (MessageBox.Show("Atualmente existem " + dtVeiculo.Rows.Count + " Veículos cadastrados para este colaborador. Deseja utilizar algum destes?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // FormBusca fb = new FormBusca(WBll.QueryBuscaVeiculosColaboradores(3).ToString(), WBll.ParametrosBuscaVeiculosColaboradores(null, null, mtxtCPF.Text), true, "VEÍCULOS DO COLABORADOR", "VEICULO", "", "Nenhum Veículo encontrado!"); // fb.ShowDialog(); // if (fb.retorno != null) // { // mtxtPlaca.Text = fb.retorno["PLACA"].ToString(); // mtxtPlaca_Leave(null, null); // } // } // } // } // } // if (!usuCartaoEstacionamento) // { // PreencherVeiculo(); // PreencherContratos(); // } // if(veiculoBicileta && !string.IsNullOrEmpty(mtxtPlaca.Text)) // { // if (AcaoFormulario == CAcaoFormulario.Novo) // btnSugerirEstacionamento_Click(sender, e); // } // } // } // else // { // MessageBox.Show("Colaborador não cadastrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Error); // txtCPFNome.Text = ""; // txtColaborador.Text = ""; // } // } // else // Acao != Novo // PreencherFormulario(); // } // else if (AcaoFormulario != CAcaoFormulario.Editar && AcaoFormulario != CAcaoFormulario.Novo) // LimpaCampos(); // else // { // txtCPFNome.Text = ""; // txtColaborador.Text = ""; // PreencherVeiculo(); // PreencherContratos(); // PreencherEstacionamentosIndicados(); // } //} //private void txtColaborador_Leave(object sender, EventArgs e) //{ // if (!usuCartaoEstacionamento) // { // if (!string.IsNullOrEmpty(txtColaborador.Text)) // { // // Se o formulário estiver na Ação Novo, trará apenas o nome, dados de CNH e Contratos do colaborador // // Se não irá procurar uma Solicitação para o CPF informado. // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // { // DataTable dt = WBll.BuscaColaboradorTrabalhando(txtColaborador.Text); // if (dt.Rows.Count > 0) // { // txtCPFNome.Text = dt.Rows[0]["NOME"].ToString(); // mtxtCPF.Text = dt.Rows[0]["CPF"].ToString(); // if (!ValidaColabRecebeValeTransp(txtColaborador.Text)) // { // txtColaborador.Text = ""; // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // txtColaborador.Focus(); // } // else if (WBll.VerificaExisteSolicitacoesPendentes(mtxtCPF.Text)) // { // MessageBox.Show("Existem solicitações pendentes para o colaborador. Verifique antes de continuar.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // txtColaborador.Text = ""; // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // mtxtCPF.Focus(); // } // else // { // DataTable dtCargoLocal = WBll.BuscaCargoLocal(txtColaborador.Text); // if (dtCargoLocal.Rows.Count > 0) // { // txtCargo.Text = dtCargoLocal.Rows[0]["ds_cargo"].ToString(); // txtLocal.Text = dtCargoLocal.Rows[0]["ds_local"].ToString(); // } // // Buscar veículos do colaborador // DataTable dtVeiculo = WBll.BuscaVeiculosColaboradores(mtxtCPF.Text, 3, null); // if (dtVeiculo.Rows.Count > 0) // { // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // if (dtVeiculo.Rows.Count == 1) // { // mtxtPlaca.Text = dtVeiculo.Rows[0]["PLACA"].ToString(); // veiculoBicileta = (dtVeiculo.Rows[0]["TIPO"].ToString().Equals("3") ? true : false); // veiculo = dtVeiculo.Rows[0]["VEICULO"].ToString(); // mtxtPlaca_Leave(null, null); // } // else // { // if (MessageBox.Show("Atualmente existem " + dtVeiculo.Rows.Count + " Veículos cadastrados para este colaborador. Deseja utilizar algum destes?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // FormBusca fb = new FormBusca(WBll.QueryBuscaVeiculosColaboradores(3).ToString(), WBll.ParametrosBuscaVeiculosColaboradores(null, null, mtxtCPF.Text), true, "VEÍCULOS DO COLABORADOR", "VEICULO", "", "Nenhum Veículo encontrado!"); // fb.ShowDialog(); // if (fb.retorno != null) // { // mtxtPlaca.Text = fb.retorno["PLACA"].ToString(); // veiculoBicileta = (fb.retorno["TIPO"].ToString().Equals("3") ? true : false); // veiculo = dtVeiculo.Rows[0]["VEICULO"].ToString(); // mtxtPlaca_Leave(null, null); // } // } // } // } // } // PreencherVeiculo(); // PreencherContratos(); // if (dtVeiculo.Rows.Count > 0) // { // if (veiculoBicileta) // { // if (dgvEstacionamentosIndicados.Rows.Count == 0) // { // if (AcaoFormulario == CAcaoFormulario.Novo) // btnSugerirEstacionamento_Click(sender, e); // } // } // } // mtxtPlaca.Focus(); // } // } // else // { // MessageBox.Show("Colaborador não cadastrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Error); // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // } // } // else // Acao != Novo // PreencherFormulario(); // } // else if (AcaoFormulario != CAcaoFormulario.Editar && AcaoFormulario != CAcaoFormulario.Novo) // LimpaCampos(); // else // { // txtCPFNome.Text = ""; // mtxtCPF.Text = ""; // PreencherVeiculo(); // PreencherContratos(); // PreencherEstacionamentosIndicados(); // } // } //} //private void txtColaborador_KeyDown(object sender, KeyEventArgs e) //{ // if (e.KeyCode == Keys.F3) // { // if (AcaoFormulario != CAcaoFormulario.Novo) // FormBuscaRegistros(sender, false); // else // Ação = Novo // { // FormBusca fb = new FormBusca(WBll.QueryBuscaColaboradorPorCPF("").ToString(), new List<System.Data.OracleClient.OracleParameter>(), true, "COLABORADORES", "NOME", txtCPFNome.Text, "Nenhum registro encontrado!", false, "NOME"); // fb.ShowDialog(); // if (fb.retorno != null) // { // txtColaborador.Text = fb.retorno["MATRICULA"].ToString(); // mtxtPlaca.Focus(); // } // } // } //} //private void txtSolicitacao_KeyDown(object sender, KeyEventArgs e) //{ // if (e.KeyCode == Keys.F3) // FormBuscaRegistros(sender, false); //} //private void txtSolicitacao_Leave(object sender, EventArgs e) //{ // if (!string.IsNullOrEmpty(txtSolicitacao.Text)) // PreencherFormulario(); // else // LimpaCampos(); //} //private void mtxtPlaca_KeyDown(object sender, KeyEventArgs e) //{ // if (e.KeyCode == Keys.F3) // { // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // FormBuscaRegistros(sender, false); // else // { // FormBusca fb = new FormBusca(WBll.QueryBuscaVeiculosColaboradores(3).ToString(), WBll.ParametrosBuscaVeiculosColaboradores(null, null, mtxtCPF.Text), true, "VEÍCULOS DE COLABORADORES", "VEICULO", "", "Nenhum Veículo encontrado!"); // fb.ShowDialog(); // if (fb.retorno != null) // mtxtPlaca.Text = fb.retorno["PLACA"].ToString(); // } // } //} //private void mtxtPlaca_Leave(object sender, EventArgs e) //{ // if (!string.IsNullOrEmpty(mtxtPlaca.Text)) // { // DataTable dt = WBll.BuscaVeiculosColaboradores(mtxtPlaca.Text, 4, mtxtCPF.Text); // //Caso o cpf não seja de colaborador, verifica se é de usuario de cartao de estacionamento // if (dt.Rows.Count == 0) // { // dt = WBll.BuscaUsuarioCartaoEstacionamento(mtxtCPF.Text); // txtObservacao.Text = dt.Rows[0]["OBSERVACAO"].ToString(); // txtContatos.Text = dt.Rows[0]["CONTATO"].ToString(); // } // if (dt.Rows.Count > 0) // { // mtxtPlaca.Text = dt.Rows[0]["PLACA"].ToString(); // mtxtPlaca.Tag = dt.Rows[0]["VEICULO"].ToString(); // veiculoBicileta = (dt.Rows[0]["TIPO"].ToString().Equals("3") ? true : false); // veiculo = dt.Rows[0]["VEICULO"].ToString(); // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // PreencherFormulario(); // } // else // { // MessageBox.Show("Veículo não Cadastrado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Error); // mtxtPlaca.Text = ""; // mtxtPlaca.Tag = ""; // } // } // else // { // if (dgvEstacionamentosIndicados.DataSource != null) // ((DataTable)dgvEstacionamentosIndicados.DataSource).Clear(); // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); // } //} //private void mtxtPlaca_Enter(object sender, EventArgs e) //{ // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // { // if (string.IsNullOrEmpty(mtxtCPF.Text)) // { // MessageBox.Show("Informe o Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // mtxtPlaca.Text = ""; // mtxtCPF.Focus(); // } // } //} //private void mtxtData_KeyDown(object sender, KeyEventArgs e) //{ // if (AcaoFormulario != CAcaoFormulario.Novo) // { // if (e.KeyCode == Keys.F3) // FormBuscaRegistros(sender, false); // } //} //private void mtxtData_Leave(object sender, EventArgs e) //{ // if (!mtxtData.Text.Equals(" / /")) // { // try // { // DateTime.Parse(mtxtData.Text); // } // catch // { // MessageBox.Show("Data inválida.", "Erro - Data Invália", MessageBoxButtons.OK, MessageBoxIcon.Information); // mtxtData.Text = ""; // return; // } // if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // PreencherFormulario(); // } // else if (AcaoFormulario != CAcaoFormulario.Novo && AcaoFormulario != CAcaoFormulario.Editar) // LimpaCampos(); //} //private void btnPlacas_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtCPF.Text)) // { // MessageBox.Show("Informe o Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // mtxtCPF.Focus(); // } // else // { // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // frmCadastroVeiculosColaboradores frmVC = new frmCadastroVeiculosColaboradores(mtxtCPF.Text, !usuCartaoEstacionamento); // frmVC.ShowInTaskbar = false; // frmVC.MinimizeBox = false; // frmVC.ShowDialog(); // if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar) // { // if (!string.IsNullOrEmpty(frmVC.retorno)) // { // mtxtPlaca.Text = frmVC.retorno; // mtxtPlaca_Leave(null, null); // } // } // } // else // { // DataTable dt = WBll.BuscaVeiculosColaboradores(mtxtPlaca.Text, 1, mtxtCPF.Text); // if (dt.Rows.Count == 1) // { // frmCadastroVeiculosColaboradores frmVC = new frmCadastroVeiculosColaboradores(int.Parse(dt.Rows[0]["VEICULO"].ToString())); // frmVC.ShowInTaskbar = false; // frmVC.MinimizeBox = false; // frmVC.ShowDialog(); // mtxtPlaca.Text = frmVC.retorno; // } // } // } //} //private void dgvContratos_CellClick(object sender, DataGridViewCellEventArgs e) //{ // if (e.RowIndex < 0) // return; // if (e.ColumnIndex == dgvContratos.Columns["colGradeHoraria"].Index) // { // if (dgvContratos.Rows[e.RowIndex].Cells["colTipcon"].Value.ToString().Equals("10")) // { // // Chama Relatório de Grade Horária do Docente (Relatório do Fox) // RelatorioSGAGradeHorariaDocente(dgvContratos.Rows[e.RowIndex].Cells["colMatricula"].Value.ToString()); // } // else // { // List<OracleParameter> parametros = new List<OracleParameter>(); // parametros.Add(new OracleParameter("matricula", dgvContratos.Rows[e.RowIndex].Cells["colMatricula"].Value.ToString())); // FormBusca fb = new FormBusca(WBll.QueryBuscaHorariosTecAdministrativo().ToString(), parametros, true, "GRADE HORÁRIA DO COLABORADOR", "CODIGO_HORA", "", "Grade Horária não encontrada", false, "CODIGO_HORA, SEQUENCIA"); // fb.ShowDialog(); // } // } //} //private void btnLiberarVaga_Click(object sender, EventArgs e) //{ // if (!ValidaCamposObrigatorios(this.Controls)) // MessageBox.Show("Por favor, preencha os campos que identificam o registro", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // else if (!mtxtCNHVencimento.Text.Equals(" / /") && DateTime.Parse(mtxtCNHVencimento.Text) < DateTime.Now) // MessageBox.Show("A CNH informada ultrapassou sua Data de Validade. Para Liberar a vaga renove o documento.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // else // { // if (dgvEstacionamentosIndicados.Rows.Count < 1) // { // MessageBox.Show("Não existem Vagas para serem liberadas!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // return; // } // if (MessageBox.Show("ATENÇÃO!! \n\n" + dgvEstacionamentosIndicados.Rows.Count + " Vaga(s) Liberada(s) serão geradas. \nTem certeza que deseja continuar?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // try // { // ClickGravar(null, null); // LiberarVaga(int.Parse(txtSolicitacao.Text)); // ClickImprimir(null, null); // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "Ocorreu um erro." + "\nContate o Administrador do Sistema para verificar o problema. \nErro: " + ex.InnerException.Message, "Erro - Liberar Vaga", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Ocorreu um erro." + "\nContate o Administrador do Sistema para verificar o problema. \nErro: " + ex.Message, "Erro - Liberar Vaga", MessageBoxButtons.OK, MessageBoxIcon.Error); // } // } // } //} //private void btnSugerirEstacionamento_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // MessageBox.Show("Informe o Veículo do Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // mtxtPlaca.Focus(); // return; // } // try // { // if (dgvEstacionamentosIndicados.Rows.Count > 0) // if (MessageBox.Show("Atenção!!\n\nGerar uma Sugestão de Estacionamentos fará com que todos os Estacionamentos Indicados existentes sejam excluídos. Tem certeza que deseja continuar?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) // return; // if (!string.IsNullOrEmpty(txtSolicitacao.Text)) // using (EntitiesPrefeituraUniversitaria mde = new EntitiesPrefeituraUniversitaria(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString())) // mde.ExecuteStoreCommand("delete from mtd.solicitacoes_estacionamentos where solicitacao = " + txtSolicitacao.Text); // if (dgvContratos.Rows.Count > 0 || usuCartaoEstacionamento) // { // DataTable dt = (DataTable)dgvContratos.DataSource; // double maiorCarga = 0.0; // DataRow[] dr = new DataRow[1]; // if (!usuCartaoEstacionamento) // { // foreach (DataRow l in dt.Rows) // { // if (double.Parse(l["CH_MENSAL"].ToString()) > maiorCarga) // maiorCarga = double.Parse(l["CH_MENSAL"].ToString()); // } // dr = dt.Select("CH_MENSAL = " + maiorCarga.ToString()); // } // if (!veiculoBicileta)//Sugestão para vagas de carros e motos // { // if (!usuCartaoEstacionamento) // { // switch (dr[0]["TIPCON"].ToString()) // { // case "10": // SugerirEstacionamentosDocente(); // break; // case "13": // SugerirEstacionamentosDocente(); // break; // default: // SugerirEstacionamentosTecADM(dr[0]["CAMPUS"].ToString(), WBll.BuscaTipoVeiculo(mtxtPlaca.Text)); // break; // } // } // } // else //sugestão para bicicleta // { // SugerirEstacionamentosBicicletas(); // } // } // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "Ocorreu um erro ao pesquisar as Sugestões de Estacionamentos. Contate o Administrador do Sistema para verificar o problema." + "\nErro: " + ex.InnerException.Message, "Erro - Sugestão Estacionamento", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Ocorreu um erro ao pesquisar as Sugestões de Estacionamentos. Contate o Administrador do Sistema para verificar o problema." + "\nErro: " + ex.Message, "Erro - Sugestão Estacionamento", MessageBoxButtons.OK, MessageBoxIcon.Error); // } //} //private void dgvEstacionamentosIndicados_CellClick(object sender, DataGridViewCellEventArgs e) //{ // if (e.RowIndex > -1 && e.ColumnIndex == dgvEstacionamentosIndicados.Columns["colExcluir"].Index) // { // if (MessageBox.Show("Tem certeza que deseja excluir o Estacionamento?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) // { // if (!string.IsNullOrEmpty(txtSolicitacao.Text)) // { // using (EntitiesPrefeituraUniversitaria mde = new EntitiesPrefeituraUniversitaria(Globals.GetStringConnectionEntity(JBll.GetModelPrefeituraUniversitaria()).ToString())) // { // long chave1 = long.Parse(txtSolicitacao.Text); // long chave2 = long.Parse(dgvEstacionamentosIndicados.Rows[e.RowIndex].Cells["colEstacionamento"].Value.ToString()); // SOLICITACOES_ESTACIONAMENTOS estacionamento = mde.SOLICITACOES_ESTACIONAMENTOS.FirstOrDefault(x => x.SOLICITACAO == chave1 && x.ESTACIONAMENTO == chave2); // if (estacionamento != null) // { // mde.DeleteObject(estacionamento); // mde.SaveChanges(); // } // } // } // ((DataTable)dgvEstacionamentosIndicados.DataSource).Rows.RemoveAt(e.RowIndex); // } // } //} //private void btnAdicionarEstacionamento_Click(object sender, EventArgs e) //{ // if (string.IsNullOrEmpty(mtxtPlaca.Text)) // { // MessageBox.Show("Informe o Veículo do Colaborador.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information); // mtxtPlaca.Focus(); // } // else // { // try // { // DataTable dtPeriodos = ((DataTable)dgvContratos.DataSource); // string manha, tarde, noite; // if (!usuCartaoEstacionamento) // { // manha = (dtPeriodos.Select("MANHA = 1").Length > 0 ? "1" : "0"); // tarde = (dtPeriodos.Select("TARDE = 1").Length > 0 ? "1" : "0"); // noite = (dtPeriodos.Select("NOITE = 1").Length > 0 ? "1" : "0"); // } // else // { // manha = "1"; // tarde = "1"; // noite = "1"; // } // FormBusca fb = new FormBusca(WBll.QueryBuscaEstacionamentosDisponiveisNaoNomeadas(false).ToString(), new List<OracleParameter>() { new OracleParameter("tipo_veiculo", WBll.BuscaTipoVeiculo(mtxtPlaca.Text)), new OracleParameter("manha", manha), new OracleParameter("tarde", tarde), new OracleParameter("noite", noite) }, true, "ESTACIONAMENTOS DISPONÍVEIS", "ESTACIONAMENTO", "", "Nenhum Estacionamento Disponível!"); // fb.ShowDialog(); // if (fb.retorno != null) // { // DataTable dt; // if (dgvEstacionamentosIndicados.DataSource == null) // { // dt = new DataTable(); // foreach (DataGridViewColumn coluna in dgvEstacionamentosIndicados.Columns) // { // if (!string.IsNullOrEmpty(coluna.DataPropertyName)) // dt.Columns.Add(coluna.DataPropertyName, typeof(string)); // } // dt.ImportRow(fb.retorno); // } // else // { // dt = ((DataTable)dgvEstacionamentosIndicados.DataSource); // dt.ImportRow(fb.retorno); // } // dt.Rows[dt.Rows.Count - 1]["SITUACAO_DESC"] = "PENDENTE"; // dt.Rows[dt.Rows.Count - 1]["MANHA"] = manha; // dt.Rows[dt.Rows.Count - 1]["TARDE"] = tarde; // dt.Rows[dt.Rows.Count - 1]["NOITE"] = noite; // dt.Rows[dt.Rows.Count - 1]["SITUACAO"] = "1"; // dgvEstacionamentosIndicados.DataSource = dt; // } // dgvEstacionamentosIndicados.Refresh(); // } // catch (Exception ex) // { // if (ex.InnerException != null) // MessageBox.Show(this, "Ocorreu um erro ao adicionar um Estacionamento. Contate o Administrador do Sistema para verificar o problema." + "\nErro: " + ex.InnerException.Message, "Erro - Adicionar Estacionamento", MessageBoxButtons.OK, MessageBoxIcon.Error); // else // MessageBox.Show(this, "Ocorreu um erro ao adicionar um Estacionamento. Contate o Administrador do Sistema para verificar o problema." + "\nErro: " + ex.Message, "Erro - Adicionar Estacionamento", MessageBoxButtons.OK, MessageBoxIcon.Error); // } // } //} //public void TratarCamposUsuCartaoEstacionamento() //{ // if (usuCartaoEstacionamento) // { // txtCargo.Enabled = false; // txtLocal.Enabled = false; // grpCNH.Enabled = false; // } // else // { // txtCargo.Enabled = true; // txtLocal.Enabled = true; // grpCNH.Enabled = true; // } //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InventorLibrary.API { public static class EnumExtensions { public static T As<T>(this InvDocumentTypeEnum c) where T : struct { return (T)System.Enum.Parse(typeof(T), c.ToString(), false); } public static T As<T>(this Inventor.DocumentTypeEnum c) where T : struct { return (T)System.Enum.Parse(typeof(T), c.ToString(), false); } public static T As<T>(this InvObjectTypeEnum c) where T : struct { return (T)System.Enum.Parse(typeof(T), c.ToString(), false); } public static T As<T>(this Inventor.ObjectTypeEnum c) where T : struct { return (T)System.Enum.Parse(typeof(T), c.ToString(), false); } } }
using CommunicatingBetweenControls.UserControls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CommunicatingBetweenControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); LoadControls(); } private void LoadControls() { var jobs = new Jobs(); jobs.SetValue(Grid.RowProperty, 1); LayoutRoot.Children.Add(jobs); var empsOnJob = new EmployeesOnJob(); var jobDetails = new JobDetails(); jobDetails.Margin = new Thickness(25, 0, 0, 0); jobDetails.SetValue(Grid.ColumnProperty, 1); ContainerGrid.Children.Add(empsOnJob); ContainerGrid.Children.Add(jobDetails); } } }
using System; namespace Union.Gateway.Abstractions.Enums { /// <summary> /// 消费者类型 /// </summary> [Flags] public enum ConsumerType : int { /// <summary> /// 消息id /// </summary> MsgIdHandlerConsumer = 1, /// <summary> /// 消息日志 /// </summary> MsgLoggingConsumer = 2, /// <summary> /// 重试消息 /// </summary> ReplyMessageConsumer = 4, /// <summary> /// 流量 /// </summary> TrafficConsumer = 8, /// <summary> /// 传输 /// </summary> TransmitConsumer = 16, /// <summary> /// 重试消息日志 /// </summary> ReplyMessageLoggingConsumer = 32, /// <summary> /// 所有 /// </summary> All = 64, } }
using System; using System.ComponentModel; using System.Linq; namespace Sitecore.Includes.AssemblyBinding.Data { /// <summary> /// Binding redirect for assembly identity /// </summary> public class BindingRedirect { /// <summary> /// The old version maximum /// </summary> private Version oldVersionMax; /// <summary> /// The old version minimum /// </summary> private Version oldVersionMin; /// <summary> /// Gets or sets the old version minimum. /// </summary> /// <value> /// The old version minimum. /// </value> public Version OldVersionMin { get { if (this.oldVersionMin != null || string.IsNullOrEmpty(this.OldVersion)) { return this.oldVersionMin; } var range = this.OldVersion.Split(new[] { '-' }, 2); if (range.Length <= 2) { var version = range.FirstOrDefault(); if (!string.IsNullOrEmpty(version) && Version.TryParse(version, out this.oldVersionMin)) { } } return this.oldVersionMin; } } /// <summary> /// Gets or sets the old version maximum. /// </summary> /// <value> /// The old version maximum. /// </value> public Version OldVersionMax { get { if (this.oldVersionMax != null || string.IsNullOrEmpty(this.OldVersion)) { return this.oldVersionMax; } var range = this.OldVersion.Split(new[] { '-' }, 2); if (range.Length <= 2) { var version = range.LastOrDefault(); if (!string.IsNullOrEmpty(version) && Version.TryParse(version, out this.oldVersionMax)) { } } return this.oldVersionMax; } } /// <summary> /// Gets or sets the old versions. /// </summary> /// <value> /// The old versions. /// </value> public string OldVersion { get; set; } /// <summary> /// Gets or sets the new version. /// </summary> /// <value> /// The new version. /// </value> [TypeConverter(typeof(VersionTypeConverter))] public Version NewVersion { get; set; } } }
using System; using System.Collections.Generic; using Hl7.Fhir.Support; using System.Xml.Linq; /* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08 // using Hl7.Fhir.Model; using System.Xml; namespace Hl7.Fhir.Parsers { /// <summary> /// Parser for Organization instances /// </summary> internal static partial class OrganizationParser { /// <summary> /// Parse Organization /// </summary> public static Organization ParseOrganization(IFhirReader reader, ErrorList errors, Organization existingInstance = null ) { Organization result = existingInstance != null ? existingInstance : new Organization(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element language else if( ParserUtils.IsAtFhirElement(reader, "language") ) result.Language = CodeParser.ParseCode(reader, errors); // Parse element text else if( ParserUtils.IsAtFhirElement(reader, "text") ) result.Text = NarrativeParser.ParseNarrative(reader, errors); // Parse element contained else if( ParserUtils.IsAtFhirElement(reader, "contained") ) { result.Contained = new List<Resource>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "contained") ) result.Contained.Add(ParserUtils.ParseContainedResource(reader,errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element identifier else if( ParserUtils.IsAtFhirElement(reader, "identifier") ) { result.Identifier = new List<Identifier>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "identifier") ) result.Identifier.Add(IdentifierParser.ParseIdentifier(reader, errors)); reader.LeaveArray(); } // Parse element name else if( ParserUtils.IsAtFhirElement(reader, "name") ) { result.Name = new List<FhirString>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "name") ) result.Name.Add(FhirStringParser.ParseFhirString(reader, errors)); reader.LeaveArray(); } // Parse element type else if( ParserUtils.IsAtFhirElement(reader, "type") ) result.Type = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element address else if( ParserUtils.IsAtFhirElement(reader, "address") ) { result.Address = new List<Address>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "address") ) result.Address.Add(AddressParser.ParseAddress(reader, errors)); reader.LeaveArray(); } // Parse element telecom else if( ParserUtils.IsAtFhirElement(reader, "telecom") ) { result.Telecom = new List<Contact>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "telecom") ) result.Telecom.Add(ContactParser.ParseContact(reader, errors)); reader.LeaveArray(); } // Parse element status else if( ParserUtils.IsAtFhirElement(reader, "status") ) result.Status = CodeParser.ParseCode<Organization.RecordStatus>(reader, errors); // Parse element accreditation else if( ParserUtils.IsAtFhirElement(reader, "accreditation") ) { result.Accreditation = new List<Organization.OrganizationAccreditationComponent>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "accreditation") ) result.Accreditation.Add(OrganizationParser.ParseOrganizationAccreditationComponent(reader, errors)); reader.LeaveArray(); } // Parse element relatedOrganization else if( ParserUtils.IsAtFhirElement(reader, "relatedOrganization") ) { result.RelatedOrganization = new List<Organization.OrganizationRelatedOrganizationComponent>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "relatedOrganization") ) result.RelatedOrganization.Add(OrganizationParser.ParseOrganizationRelatedOrganizationComponent(reader, errors)); reader.LeaveArray(); } // Parse element contactPerson else if( ParserUtils.IsAtFhirElement(reader, "contactPerson") ) { result.ContactPerson = new List<Organization.OrganizationContactPersonComponent>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "contactPerson") ) result.ContactPerson.Add(OrganizationParser.ParseOrganizationContactPersonComponent(reader, errors)); reader.LeaveArray(); } else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } /// <summary> /// Parse OrganizationRelatedOrganizationComponent /// </summary> public static Organization.OrganizationRelatedOrganizationComponent ParseOrganizationRelatedOrganizationComponent(IFhirReader reader, ErrorList errors, Organization.OrganizationRelatedOrganizationComponent existingInstance = null ) { Organization.OrganizationRelatedOrganizationComponent result = existingInstance != null ? existingInstance : new Organization.OrganizationRelatedOrganizationComponent(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element organization else if( ParserUtils.IsAtFhirElement(reader, "organization") ) result.Organization = ResourceReferenceParser.ParseResourceReference(reader, errors); // Parse element relation else if( ParserUtils.IsAtFhirElement(reader, "relation") ) result.Relation = CodeableConceptParser.ParseCodeableConcept(reader, errors); else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } /// <summary> /// Parse OrganizationContactPersonComponent /// </summary> public static Organization.OrganizationContactPersonComponent ParseOrganizationContactPersonComponent(IFhirReader reader, ErrorList errors, Organization.OrganizationContactPersonComponent existingInstance = null ) { Organization.OrganizationContactPersonComponent result = existingInstance != null ? existingInstance : new Organization.OrganizationContactPersonComponent(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element type else if( ParserUtils.IsAtFhirElement(reader, "type") ) result.Type = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element details else if( ParserUtils.IsAtFhirElement(reader, "details") ) result.Details = DemographicsParser.ParseDemographics(reader, errors); else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } /// <summary> /// Parse OrganizationAccreditationComponent /// </summary> public static Organization.OrganizationAccreditationComponent ParseOrganizationAccreditationComponent(IFhirReader reader, ErrorList errors, Organization.OrganizationAccreditationComponent existingInstance = null ) { Organization.OrganizationAccreditationComponent result = existingInstance != null ? existingInstance : new Organization.OrganizationAccreditationComponent(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element identifier else if( ParserUtils.IsAtFhirElement(reader, "identifier") ) result.Identifier = IdentifierParser.ParseIdentifier(reader, errors); // Parse element code else if( ParserUtils.IsAtFhirElement(reader, "code") ) result.Code = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element issuer else if( ParserUtils.IsAtFhirElement(reader, "issuer") ) result.Issuer = ResourceReferenceParser.ParseResourceReference(reader, errors); // Parse element period else if( ParserUtils.IsAtFhirElement(reader, "period") ) result.Period = PeriodParser.ParsePeriod(reader, errors); else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } } }
namespace iSukces.Code.Irony { internal sealed class Exchange { public const string MethodForEvaluatingPropertyKey = "=MethodForEvaluatingProperty="; public const string X = "=MethodForEvaluatingProperty="; public sealed class MethodForEvaluatingProperty { public MethodForEvaluatingProperty(string propertyName, string methodName, bool needThreadVariable) { PropertyName = propertyName; MethodName = methodName; NeedThread = needThreadVariable; } public string PropertyName { get; } public string MethodName { get; } public bool NeedThread { get; } } public sealed class Du { public string GetNodeKindMethodName { get; } public Du(string getNodeKindMethodName) { GetNodeKindMethodName = getNodeKindMethodName; } } } }
using Ardalis.Specification; using System; using System.Linq; using WritingPlatformCore.Entities; namespace WritingPlatformCore.Specifications { public class CatalogItemsSpecification : Specification<CatalogItem> { public CatalogItemsSpecification(params int[] ids) { Query.Where(c => ids.Contains(c.Id)); } } }
namespace ChallengeTechAndSolve.Mappers { using ChallengeTechAndSolve.Business.Models; using ChallengeTechAndSolve.ViewModels; public static class ParticipantInformationMapper { public static ParticipantInformationDto Map(this ParticipantInformationViewModel dto) { return new ParticipantInformationDto() { Document = dto.Document, FileInfo = dto.File, }; } public static ParticipantInformationViewModel Map(this ParticipantInformationDto entity) { return new ParticipantInformationViewModel() { Document = entity.Document, File = entity.FileInfo, }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using iTextSharp.text; using System.Reflection; using iTextSharp.text.pdf; namespace QuanLySinhVien { public partial class LapDanhSachGiaoVienDay : Form { public LapDanhSachGiaoVienDay() { InitializeComponent(); } private void LapDanhSachGiaoVienDay_FormClosed(object sender, FormClosedEventArgs e) { QuanLyHeThong qlht = new QuanLyHeThong(); qlht.Show(); this.Hide(); } private void button1_Click(object sender, EventArgs e) { PdfPTable pdfPTable = new PdfPTable(dataGridView1.ColumnCount); pdfPTable.DefaultCell.Padding = 3; pdfPTable.WidthPercentage = 30; pdfPTable.HorizontalAlignment = Element.ALIGN_LEFT; pdfPTable.DefaultCell.BorderWidth = 1; foreach (DataGridViewColumn column in dataGridView1.Columns) { PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText)); cell.BackgroundColor = new BaseColor(240,240,240); pdfPTable.AddCell(cell); } foreach (DataGridViewRow row in dataGridView1.Rows) { foreach (DataGridViewCell cell in row.Cells) { pdfPTable.AddCell(cell.Value.ToString()); } } Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("C:\\Users\\Hieu Koi\\Desktop\\xuatpfile.pdf", FileMode.Create)); doc.Open(); Paragraph par = new Paragraph("this is my paragreap"); doc.Add(par); doc.Add(pdfPTable); doc.Close(); MessageBox.Show("bạn đã xuất file pdf thành công !"); } } }
using System; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.SYS; namespace com.Sconit.Entity.SI.SAP { [Serializable] public partial class SAPPPMES0006 : EntityBase { #region O/R Mapping Properties public Int32 Id { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 10)] [Display(Name = "SAPPPMES_ZMESSC", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ZMESSC { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 20)] [Display(Name = "SAPPPMES_ZMESLN", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ZMESLN { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 30)] [Display(Name = "SAPPPMES_ZPTYPE", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ZPTYPE { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 40)] [Display(Name = "SAPPPMES_AUFNR", ResourceType = typeof(Resources.SI.SAPPPMES))] public string AUFNR { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 45)] [Display(Name = "SAPPPMES_WERKS", ResourceType = typeof(Resources.SI.SAPPPMES))] public string WERKS { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 80)] [Display(Name = "SAPPPMES_BWART", ResourceType = typeof(Resources.SI.SAPPPMES))] public string BWART { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 80)] [Display(Name = "SAPPPMES_BWART_F", ResourceType = typeof(Resources.SI.SAPPPMES))] public string BWART_F { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 80)] [Display(Name = "SAPPPMES_BWART_S", ResourceType = typeof(Resources.SI.SAPPPMES))] public string BWART_S { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 90)] [Display(Name = "SAPPPMES_NPLNR", ResourceType = typeof(Resources.SI.SAPPPMES))] public string NPLNR { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 100)] [Display(Name = "SAPPPMES_VORNR", ResourceType = typeof(Resources.SI.SAPPPMES))] public string VORNR { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 110)] [Display(Name = "SAPPPMES_RSNUM", ResourceType = typeof(Resources.SI.SAPPPMES))] public string RSNUM { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 120)] [Display(Name = "SAPPPMES_RSPOS", ResourceType = typeof(Resources.SI.SAPPPMES))] public string RSPOS { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 130)] [Display(Name = "SAPPPMES_MATNR1", ResourceType = typeof(Resources.SI.SAPPPMES))] public string MATNR1 { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 120)] [Display(Name = "SAPPPMES_MTSNR", ResourceType = typeof(Resources.SI.SAPPPMES))] public string MTSNR { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 120)] [Display(Name = "SAPPPMES_LFSNR", ResourceType = typeof(Resources.SI.SAPPPMES))] public string LFSNR { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 110)] [Display(Name = "SAPPPMES_BLDAT", ResourceType = typeof(Resources.SI.SAPPPMES))] public DateTime BLDAT { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 110)] [Display(Name = "SAPPPMES_BUDAT", ResourceType = typeof(Resources.SI.SAPPPMES))] public DateTime BUDAT { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 140)] [Display(Name = "SAPPPMES_EPFMG", ResourceType = typeof(Resources.SI.SAPPPMES))] public string EPFMG { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 150)] [Display(Name = "SAPPPMES_ERFME", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ERFME { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 50)] [Display(Name = "SAPPPMES_ZComnum", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ZComnum { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 60)] [Display(Name = "SAPPPMES_LMNGA_H", ResourceType = typeof(Resources.SI.SAPPPMES))] public string LMNGA_H { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 60)] [Display(Name = "SAPPPMES_LGORT", ResourceType = typeof(Resources.SI.SAPPPMES))] public string LGORT { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 70)] [Display(Name = "SAPPPMES_ISM", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ISM { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 160)] [Display(Name = "SAPPPMES_ZMESGUID", ResourceType = typeof(Resources.SI.SAPPPMES))] public string ZMESGUID { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 170)] [Display(Name = "SAPPPMES_ZCSRQSJ", ResourceType = typeof(Resources.SI.SAPPPMES))] public DateTime ZCSRQSJ { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 200)] [Display(Name = "SAPPPMES_Status", ResourceType = typeof(Resources.SI.SAPPPMES))] public Int32 Status { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 180)] [Display(Name = "SAPPPMES_BatchNo", ResourceType = typeof(Resources.SI.SAPPPMES))] public string BatchNo { get; set; } [Export(ExportName = "SAPPPMES0006", ExportSeq = 190)] [Display(Name = "SAPPPMES_UniqueCode", ResourceType = typeof(Resources.SI.SAPPPMES))] public string UniqueCode { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { SAPPPMES0006 another = obj as SAPPPMES0006; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Services; using System.Web.Services; using BLL; using BLL.MediosMagneticos; using Entidades.Vistas; using ByA; namespace webSignusL.Servicios { /// <summary> /// Descripción breve de wsMediosMagneticos /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente. [System.Web.Script.Services.ScriptService] public class wsMediosMagneticos : System.Web.Services.WebService { [WebMethod(EnableSession = true)] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public ByARpt Insert(string Periodo, string Vigencia, string AgenteRecaudador) { MediosMagneticosBLL oMMG = new MediosMagneticosBLL(); return oMMG.Insert(Periodo, Vigencia, AgenteRecaudador); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CircleAttraction : MonoBehaviour { public float radius; public Transform[] allPOI; public int valueCircle; public bool repulse = false; public Vector3 DirFromAngle(float angleDegrees){ return new Vector3(Mathf.Sin(angleDegrees * Mathf.Deg2Rad), 0, Mathf.Cos(angleDegrees = Mathf.Deg2Rad)); } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using MassTransit; using Meetup.Errors.Contracts; using Serilog; namespace Meetup.Errors.ServiceCaller { internal class CallExternalProcessCommandHandler : IConsumer<CallExternalProcess> { public async Task Consume(ConsumeContext<CallExternalProcess> context) { Log.Information("Calling external service {index}", context.Message.Index); var client = new HttpClient(); var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3)); var result = await client.GetAsync("http://localhost:5000/api/faulty", cancellationTokenSource.Token); result.EnsureSuccessStatusCode(); var response = await result.Content.ReadAsStringAsync(); Log.Information("Received result : {response}", response); } } }
using System.Collections; public interface IBullet { void checkEnds(); void move(); void bulletSpecial(); IEnumerator bulletCoroutine(); }
namespace TripDestination.Web.MVC.Areas.Admin.ViewModels { using Common.Infrastructure.Mapping; using Data.Models; using System; using System.Collections.Generic; public class NotificationTypeAdminViewModel : IMapFrom<NotificationType> { public int Id { get; set; } public string Description { get; set; } public NotificationKey Key { get; set; } } }
using System; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace HealthVault.Sample.Xamarin.Core.ViewModels.ViewRows { public class MenuItemViewRow : BindableObject { private bool _opening; public MenuItemViewRow() { OpenCommand = new Command(async o => await PageAction()); } public ICommand OpenCommand { get; } public ImageSource Image { get; set; } public string Title { get; set; } public string Description { get; set; } public Color BackgroundColor { get; set; } public bool Opening { get { return _opening; } set { _opening = value; OnPropertyChanged(); } } public Func<Task> PageAction { get; set; } } }
using Niusys.WebAPI.Common.Filters; using Niusys.WebAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Niusys.WebAPI.Controllers { [RoutePrefix("api/products"), SessionValidate] public class ProductController : ApiController { [HttpGet] public void ProductsAPI() { } /// <summary> /// 产品分页数据获取 /// </summary> /// <returns></returns> [HttpGet, Route("product/getList")] public Page<Product> GetProductList(string sessionKey) { return new Page<Product>(); } /// <summary> /// 获取单个产品 /// </summary> /// <param name="productId"></param> /// <returns></returns> [HttpGet, Route("product/get")] public Product GetProduct(string sessionKey, Guid productId) { return new Product() { ProductId = productId }; } /// <summary> /// 添加产品 /// </summary> /// <param name="product"></param> /// <returns></returns> [HttpPost, Route("product/add")] public Guid AddProduct(string sessionKey, Product product) { return Guid.NewGuid(); } /// <summary> /// 更新产品 /// </summary> /// <param name="productId"></param> /// <param name="product"></param> [HttpPost, Route("product/update")] public void UpdateProduct(string sessionKey, Guid productId, Product product) { } /// <summary> /// 删除产品 /// </summary> /// <param name="productId"></param> [HttpDelete, Route("product/delete")] public void DeleteProduct(string sessionKey, Guid productId) { } } }
 using System; using System.Collections.Generic; using Microsoft.Bot.Builder.AI.Luis; using Microsoft.Bot.Builder.AI.QnA; using Microsoft.Bot.Configuration; namespace ChatBot.Domain.Services.IA { public class BotServices { [Obsolete] public BotServices(BotConfiguration botConfiguration) { foreach (var service in botConfiguration.Services) { switch (service.Type) { case ServiceTypes.Luis: { var luis = (LuisService)service ?? throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file."); var app = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint()); var recognizer = new LuisRecognizer(app); LuisServices.Add(luis.Name, recognizer); break; } case ServiceTypes.QnA: { var qna = (QnAMakerService)service ?? throw new InvalidOperationException("The Qna service is not configured correctly in your '.bot' file."); var qnaMaker = new QnAMaker( new QnAMakerEndpoint { EndpointKey = qna.EndpointKey, Host = qna.Hostname, KnowledgeBaseId = qna.KbId }, new QnAMakerOptions { Top = 1, ScoreThreshold = 0.5f }); QnAServices.Add(qna.Name, qnaMaker); break; } } } } public Dictionary<string, LuisRecognizer> LuisServices { get; } = new Dictionary<string, LuisRecognizer>(); public Dictionary<string, QnAMaker> QnAServices { get; } = new Dictionary<string, QnAMaker>(); } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Microsoft.AspNetCore.Rewrite; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Authentication.JwtBearer; using Data; using Data.Entities; using Library; using Library.Interfaces; using Data.Repositories; using App.Service; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; using Okta.AspNetCore; namespace WikiRacing { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string connectionString = Configuration.GetConnectionString("Project2"); services.AddSingleton<ITokenService, TokenService>(); services.Configure<App.OktaConfig>(Configuration.GetSection("Okta")); services.AddDbContext<Project2Context>(options => { options.UseSqlServer(connectionString); }); services.AddScoped<Library.Interfaces.IRaceRepository, Data.Repositories.RaceRepository>(); services.AddScoped<Library.Interfaces.IUserRepository, Data.Repositories.UserRepository>(); services.AddScoped<Library.Interfaces.ILeaderBoardLineRepository, Data.Repositories.LeaderboardLineRepository>(); services.AddScoped<App.Service.WebScraperService>(); services.AddCors(options => options.AddDefaultPolicy(config => config .WithOrigins("http://localhost:4200", "https://team4-project2-client.azurewebsites.net") .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials())); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://dev-50964723.okta.com/oauth2/default"; options.Audience = "api://default"; }); services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.AddPolicy("AllowedAddresses", policy => policy.RequireAssertion(context => { var allowed = (IEnumerable<string>)context.Resource; string userAddress = context.User.FindFirstValue(ClaimTypes.NameIdentifier); return allowed.Contains(userAddress); })); }); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WikiRacing", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WikiRacing v1")); } app.UseStatusCodePages(); app.UseHttpsRedirection(); app.UseRewriter(new RewriteOptions() .AddRedirect("^$", "dashboard")); app.UseStaticFiles(); app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using System; using System.Xml; using Breeze.Helpers; using Breeze.Screens; using Breeze.Services.InputService; using Breeze.AssetTypes.DataBoundTypes; using Breeze.AssetTypes.XMLClass; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Breeze.AssetTypes { public class BoxShadowAsset : DataboundContainterAsset { public BoxShadowAsset() { } public BoxShadowAsset(Color color, float borderSize, FloatRectangle position) { Color.Value = color; BorderSizePercentage.Value = borderSize; Position.Value = position; } internal void Update(BoxShadowAsset rectangleAsset) { Color = rectangleAsset.Color; BorderSizePercentage = rectangleAsset.BorderSizePercentage; Position = rectangleAsset.Position; } //public override void LoadFromXml(XmlAttributeCollection childNodeAttributes) //{ // if (childNodeAttributes.GetNamedItem("Position")?.Value != null) Position = UIElement.GetDBValue<FloatRectangle>(childNodeAttributes.GetNamedItem("Position")?.Value); // if (childNodeAttributes.GetNamedItem("BackgroundColor")?.Value != null) BackgroundColor = UIElement.GetDBValue<Color?>(childNodeAttributes.GetNamedItem("BackgroundColor")?.Value); // if (childNodeAttributes.GetNamedItem("Color")?.Value != null) Color = UIElement.GetDBValue<Color>(childNodeAttributes.GetNamedItem("Color")?.Value); // if (childNodeAttributes.GetNamedItem("TileMode")?.Value != null) TileMode = UIElement.GetDBValue<TileMode>(childNodeAttributes.GetNamedItem("TileMode")?.Value); // if (childNodeAttributes.GetNamedItem("BorderSizePercentage")?.Value != null) BorderSizePercentage = UIElement.GetDBValue<float>(childNodeAttributes.GetNamedItem("BorderSizePercentage")?.Value); // if (childNodeAttributes.GetNamedItem("Scale")?.Value != null) Scale = UIElement.GetDBValue<float>(childNodeAttributes.GetNamedItem("Scale")?.Value); //} //public DataboundValue<FloatRectangle> Position { get; set; } = new DataboundValue<FloatRectangle>(); [System.Xml.Serialization.XmlAttributeAttribute()] public DataboundValue<TileMode> TileMode { get; set; } = new DataboundValue<TileMode>(); //[System.Xml.Serialization.XmlAttributeAttribute()] //public DataboundValue<string> FillTexture { get; set; } = new DataboundValue<string>(null,null); [System.Xml.Serialization.XmlAttributeAttribute()] public DataboundValue<Color?> BackgroundColor { get; set; } = new DataboundValue<Color?>(); [System.Xml.Serialization.XmlAttributeAttribute()] public DataboundValue<Color> Color { get; set; } = new DataboundValue<Color>(); [System.Xml.Serialization.XmlAttributeAttribute()] public DataboundValue<float> BorderSizePercentage { get; set; } = new DataboundValue<float>(); [System.Xml.Serialization.XmlAttributeAttribute()] public DataboundValue<float> Scale { get; set; } = new DataboundValue<float>(1f); public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null) { using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch)) { Rectangle tmp = screen.Translate(Position.Value.Move(scrollOffset)).ToRectangle().Clip(screen.Translate(clip)); int borderSize = (int) (Math.Min(tmp.Width, tmp.Height) * BorderSizePercentage.Value); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\tl.png"), new Rectangle(tmp.X - borderSize, tmp.Y - borderSize, borderSize, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\tr.png"), new Rectangle(tmp.Right, tmp.Y - borderSize, borderSize, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\bl.png"), new Rectangle(tmp.X - borderSize, tmp.Bottom, borderSize, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\br.png"), new Rectangle(tmp.Right, tmp.Bottom, borderSize, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\t.png"), new Rectangle(tmp.X, tmp.Y - borderSize, tmp.Width, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\b.png"), new Rectangle(tmp.X, tmp.Bottom, tmp.Width, borderSize), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\l.png"), new Rectangle(tmp.X - borderSize, tmp.Y, borderSize, tmp.Height), Color.Value * opacity); spriteBatch.Draw(Solids.Instance.AssetLibrary.GetTexture("Images\\9grid\\r.png"), new Rectangle(tmp.Right, tmp.Y, borderSize, tmp.Height), Color.Value * opacity); } SetChildrenOriginToMyOrigin(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2_harmadik_feladat { class Program { static string LegrosszabbAuto(byte[] allapot, string[] rendszam) { byte legrosszabbAuto = allapot.Min(); int legrosszabbAutoIndexe = Array.IndexOf(allapot, legrosszabbAuto); string legrosszabbAutoRendszama = rendszam[legrosszabbAutoIndexe]; string eredmeny = "A legrosszabb állapotban levő autó rendszáma: " + legrosszabbAutoRendszama + ", melynek állapot értéke: " + legrosszabbAuto + "."; return eredmeny; } static void Main(string[] args) { int bekertSzam; do { Console.WriteLine("Kérlek írd be hány autót akarsz felvinni!"); } while (!int.TryParse(Console.ReadLine(), out bekertSzam)); string[] rendszam = new string[bekertSzam]; byte[] allapot = new byte[bekertSzam]; for (int i = 0; i < bekertSzam; i++) { Console.WriteLine("Kérlek írd be az " + i + 1 + ". autó rendszámát!"); rendszam[i] = Console.ReadLine(); do { Console.WriteLine("Kérlek írd be az autó állapot értékét (0 - 100)!"); } while (!byte.TryParse(Console.ReadLine(), out allapot[i]) || allapot[i] > 100 || allapot[i] < 0); } Console.WriteLine(LegrosszabbAuto(allapot, rendszam)); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; namespace Blog { public class SqlHelper { public static DataTable GetDataBySql(string sql) { string sqlcon = @"Data Source=.;Initial Catalog=myblog;User ID=sa;Password=123456"; SqlConnection scon = new SqlConnection(sqlcon); if (scon.State != ConnectionState.Open) { scon.Open(); } SqlCommand scmd=new SqlCommand(); scmd.Connection = scon; scmd.CommandText = sql; scmd.CommandType = CommandType.Text; SqlDataAdapter sda=new SqlDataAdapter(); DataTable dt = new DataTable(); sda.SelectCommand = scmd; sda.Fill(dt); return dt; } public static bool ExecuteSql(string sql) { string sqlConnection = @"Data Source=.;Initial Catalog=myblog;User ID=sa;Password=123456"; SqlConnection scon = new SqlConnection(sqlConnection); if (scon.State != ConnectionState.Open) { scon.Open(); } SqlCommand scmd=new SqlCommand(); scmd.Connection = scon; scmd.CommandText = sql; scmd.CommandType = CommandType.Text; if (scmd.ExecuteNonQuery() > 0) { return true; } return false; } } }
namespace Swan.Ldap { /// <summary> /// LDAP Operation. /// </summary> internal enum LdapOperation { /// <summary> /// The unknown /// </summary> Unknown = -1, /// <summary> /// A bind request operation. /// BIND_REQUEST = 0 /// </summary> BindRequest = 0, /// <summary> /// A bind response operation. /// BIND_RESPONSE = 1 /// </summary> BindResponse = 1, /// <summary> /// An unbind request operation. /// UNBIND_REQUEST = 2 /// </summary> UnbindRequest = 2, /// <summary> /// A search request operation. /// SEARCH_REQUEST = 3 /// </summary> SearchRequest = 3, /// <summary> /// A search response containing data. /// SEARCH_RESPONSE = 4 /// </summary> SearchResponse = 4, /// <summary> /// A search result message - contains search status. /// SEARCH_RESULT = 5 /// </summary> SearchResult = 5, /// <summary> /// A modify request operation. /// MODIFY_REQUEST = 6 /// </summary> ModifyRequest = 6, /// <summary> /// A modify response operation. /// MODIFY_RESPONSE = 7 /// </summary> ModifyResponse = 7, /// <summary> /// An abandon request operation. /// ABANDON_REQUEST = 16 /// </summary> AbandonRequest = 16, /// <summary> /// A search result reference operation. /// SEARCH_RESULT_REFERENCE = 19 /// </summary> SearchResultReference = 19, /// <summary> /// An extended request operation. /// EXTENDED_REQUEST = 23 /// </summary> ExtendedRequest = 23, /// <summary> /// An extended response operation. /// EXTENDED_RESPONSE = 24 /// </summary> ExtendedResponse = 24, /// <summary> /// An intermediate response operation. /// INTERMEDIATE_RESPONSE = 25 /// </summary> IntermediateResponse = 25, } /// <summary> /// ASN1 tags. /// </summary> internal enum Asn1IdentifierTag { /// <summary> /// Universal tag class. /// </summary> Universal = 0, /// <summary> /// Application-wide tag class. /// </summary> Application = 1, /// <summary> /// Context-specific tag class. /// </summary> Context = 2, /// <summary> /// Private-use tag class. /// </summary> Private = 3, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UICanvas : MonoBehaviour { public Transform iconContainer; public GameObject hitSoundPrefab, enemyHitSoundPrefab, peHitSoundPrefab; public UIExplosionEffect explosionPrefab; public void SpawnHitSound(Vector3 pos, bool byEnemy) { var temp = Instantiate(byEnemy ? enemyHitSoundPrefab : hitSoundPrefab, transform); temp.transform.position = pos; } public void SpawnPEHitSound(Vector3 pos) { var temp = Instantiate(peHitSoundPrefab, transform); temp.transform.position = pos; } public void SpawnExplosionSound(Vector3 worldPos) { var temp = Instantiate(explosionPrefab, transform); temp.sourcePos = worldPos; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SlerpFollow : MonoBehaviour { [SerializeField] public float minDistance; [SerializeField] public float followCoefficient; [SerializeField] public Transform target; // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 a = transform.position; Vector3 b = target.position; Vector3 next; if (Vector3.Distance (a, b) < minDistance) { // Debug.Log ("Setting Distance Directly"); next = b; } else { next = ((b - a) * followCoefficient) + a; } transform.position = next; } }
using System; using System.Collections.Generic; using System.Text; namespace jaytwo.Common.Time { public static class TimeProvider { private static ITimeProvider _provider; public static void SetProvider(ITimeProvider provider) { _provider = provider; } private static void SetDefaultProviderIfNotSet() { if (_provider == null) { SetProvider(new DefaultTimeProvider()); } } public static DateTime Now { get { SetDefaultProviderIfNotSet(); return _provider.Now; } } public static DateTime UtcNow { get { SetDefaultProviderIfNotSet(); return _provider.UtcNow; } } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; public class IcePath_GenerateFog : MonoBehaviour { // Fog-related variables [Header("Fog-related")] [SerializeField] private GameObject prefabFog; [SerializeField] private float fogTime; float fogAlarm; // Bring in static variables int mapDiff; Vector2 origin; void Awake() { // Assign static variables mapDiff = IcePath_Master.globalMapDiff; origin = IcePath_Master.globalOrigin; } void Start () { // Spawn a few fog at first if (mapDiff == 3) { int n = 32; while (n > 0) { Instantiate(prefabFog, new Vector2(rand(-16, 16), rand(-12, 12)), Quaternion.identity); n--; } } } void Update () { } int rand (float min, float max) { // Return: round random range value return (Mathf.RoundToInt(Random.Range(min, max))); } }
using Data.Models.Interfaces; using System.Collections.Generic; using System.Linq; namespace Data.Models { public class Profile : IModel, IIdentifier { public int Id { get; set; } public string Description { get; set; } public virtual ICollection<ProfileFeature> ProfileFeatures { get; set; } = new List<ProfileFeature>(); public virtual ICollection<Feature> Features => this.ProfileFeatures.Select(x => x.Feature).ToList(); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; namespace Game.UI { /// <summary> /// 自动更改画布大小:根据不同设备予以UI不同的显示模式 /// </summary> public class MyUICanvasScaler : MonoBehaviour { public static float g_preferSizeX = 800; public static float g_preferSizeY = 600; // Use this for initialization void Awake() { #if MOBILE_INPUT || UNITY_EDITOR //先判断是否iPad: bool isIpad = false; UnityEngine.iOS.DeviceGeneration ipGen = UnityEngine.iOS.Device.generation; switch (ipGen) { case UnityEngine.iOS.DeviceGeneration.iPad1Gen: case UnityEngine.iOS.DeviceGeneration.iPad2Gen: case UnityEngine.iOS.DeviceGeneration.iPad3Gen: case UnityEngine.iOS.DeviceGeneration.iPad4Gen: case UnityEngine.iOS.DeviceGeneration.iPadAir1: case UnityEngine.iOS.DeviceGeneration.iPadAir2: case UnityEngine.iOS.DeviceGeneration.iPadMini1Gen: case UnityEngine.iOS.DeviceGeneration.iPadMini2Gen: case UnityEngine.iOS.DeviceGeneration.iPadMini3Gen: case UnityEngine.iOS.DeviceGeneration.iPadMini4Gen: case UnityEngine.iOS.DeviceGeneration.iPadPro1Gen: case UnityEngine.iOS.DeviceGeneration.iPadUnknown: isIpad = true; break; } //--再根据大小给定画布值 //移动端时: CanvasScaler scaler = GetComponent<CanvasScaler>(); Vector2 wantResolution; if (isIpad == false) { //手持设备: if (Screen.width > 2048) { wantResolution.x = 1366; wantResolution.y = 768; } else if (Screen.width > 1024) { wantResolution.x = 1136; wantResolution.y = 640; } else { wantResolution.x = 800; wantResolution.y = 600; } } else { //iPad: //scaler.referenceResolution = new Vector2(Screen.width, Screen.width * 0.5625F); wantResolution.x = 2048; wantResolution.y = 1152; } scaler.referenceResolution = wantResolution; g_preferSizeX = wantResolution.x; g_preferSizeY = wantResolution.y; #else //非移动端时 GetComponent<CanvasScaler>().referenceResolution = new Vector2(Screen.width, Screen.height); #endif } #if UNITY_EDITOR // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.P)) { Debug.Log("更改为PC UI:"); GetComponent<CanvasScaler>().referenceResolution = new Vector2(1366, 768); } else if (Input.GetKeyDown(KeyCode.M)) { Debug.Log("更改为Mobile UI:"); GetComponent<CanvasScaler>().referenceResolution = new Vector2(800, 600); } else if (Input.GetKeyDown(KeyCode.I)) { Debug.Log("Ipad"); GetComponent<CanvasScaler>().referenceResolution = new Vector2(2048, 1152); } } #endif } }
using System; using System.Threading.Tasks; using Cocona; using Microsoft.Extensions.DependencyInjection; using PlatformStatusTracker.Core.Configuration; using PlatformStatusTracker.Core.Enum; using PlatformStatusTracker.Core.Model; using PlatformStatusTracker.Core.Repository; namespace PlatformStatusTracker.Updater { class Program { static void Main(string[] args) { CoconaApp.Create() .ConfigureServices((hostContext, services) => { services.Configure<ConnectionStringOptions>(hostContext.Configuration); services.AddTransient<IChangeSetRepository, ChangeSetAzureStorageRepository>(); services.AddTransient<IStatusRawDataRepository, StatusRawDataAzureStorageRepository>(); services.AddTransient<DataUpdateAgent>(); }) .Run<Program>(args); } public async Task UpdateDaily([FromService] DataUpdateAgent agent) { await agent.UpdateAllAsync(); } public async Task UpdateRange([FromService] DataUpdateAgent agent, [Option('t')]StatusDataType statusDataType, DateTime from, DateTime to) { await agent.UpdateChangeSetByRangeAsync(statusDataType, from, to); } } }
using UnityEngine; public class SyncHuman : BaseSimpleSampleCharacterControl { private Vector3 lastPos; private Vector3 lastRot; public Vector3 forecastPos; public Vector3 forecastRot; private float forecastTime; // Use this for initialization private void Start() { //初始化预测信息 lastPos = transform.position; lastRot = transform.eulerAngles; forecastPos = transform.position; forecastRot = transform.eulerAngles; forecastTime = Time.time; } private new void Update() { base.Update(); ForecastUpdate(); } private void ForecastUpdate() { //时间 float t = (Time.time - forecastTime) / CtrlHuman.syncInterval; t = Mathf.Clamp(t, 0f, 1f); //位置 Vector3 pos = transform.position; pos = Vector3.Lerp(pos, forecastPos, t); transform.position = pos; //旋转 Quaternion quat = transform.rotation; Quaternion forcastQuat = Quaternion.Euler(forecastRot); quat = Quaternion.Lerp(quat, forcastQuat, t); transform.rotation = quat; } /// <summary> /// 移动同步 /// </summary> /// <param name="msg"></param> public void SyncPos(MsgMove msg) { Vector3 pos = new Vector3(msg.x, msg.y, msg.z); Vector3 rot = new Vector3(msg.ex, msg.ey, msg.ez); forecastPos = pos + 2 * (pos - lastPos); forecastRot = rot + 2 * (rot - lastRot); //更新 lastPos = pos; lastPos = rot; forecastTime = Time.time; } }
using Sentry.Extensibility; using Sentry.Internal.Extensions; namespace Sentry; /// <summary> /// An interface which describes the authenticated User for a request. /// </summary> /// <see href="https://develop.sentry.dev/sdk/event-payloads/user/"/> public sealed class User : IJsonSerializable { internal Action<User>? PropertyChanged { get; set; } private string? _id; private string? _username; private string? _email; private string? _ipAddress; private string? _segment; private IDictionary<string, string>? _other; /// <summary> /// The unique ID of the user. /// </summary> public string? Id { get => _id; set { _id = value; PropertyChanged?.Invoke(this); } } /// <summary> /// The username of the user. /// </summary> public string? Username { get => _username; set { _username = value; PropertyChanged?.Invoke(this); } } /// <summary> /// The email address of the user. /// </summary> public string? Email { get => _email; set { _email = value; PropertyChanged?.Invoke(this); } } /// <summary> /// The IP address of the user. /// </summary> public string? IpAddress { get => _ipAddress; set { _ipAddress = value; PropertyChanged?.Invoke(this); } } /// <summary> /// The segment the user belongs to. /// </summary> public string? Segment { get => _segment; set { _segment = value; PropertyChanged?.Invoke(this); } } /// <summary> /// Additional information about the user. /// </summary> public IDictionary<string, string> Other { get => _other ??= new Dictionary<string, string>(); set { _other = value; PropertyChanged?.Invoke(this); } } /// <summary> /// Clones the current <see cref="User"/> instance. /// </summary> /// <returns>The cloned user.</returns> public User Clone() { var user = new User(); CopyTo(user); return user; } internal void CopyTo(User? user) { if (user == null) { return; } user.Id ??= Id; user.Username ??= Username; user.Email ??= Email; user.IpAddress ??= IpAddress; user.Segment ??= Segment; user._other ??= _other?.ToDictionary( entry => entry.Key, entry => entry.Value); } internal bool HasAnyData() => Id is not null || Username is not null || Email is not null || IpAddress is not null || Segment is not null || _other?.Count > 0; /// <inheritdoc /> public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? _) { writer.WriteStartObject(); writer.WriteStringIfNotWhiteSpace("id", Id); writer.WriteStringIfNotWhiteSpace("username", Username); writer.WriteStringIfNotWhiteSpace("email", Email); writer.WriteStringIfNotWhiteSpace("ip_address", IpAddress); writer.WriteStringIfNotWhiteSpace("segment", Segment); writer.WriteStringDictionaryIfNotEmpty("other", _other!); writer.WriteEndObject(); } /// <summary> /// Parses from JSON. /// </summary> public static User FromJson(JsonElement json) { var id = json.GetPropertyOrNull("id")?.GetString(); var username = json.GetPropertyOrNull("username")?.GetString(); var email = json.GetPropertyOrNull("email")?.GetString(); var ip = json.GetPropertyOrNull("ip_address")?.GetString(); var segment = json.GetPropertyOrNull("segment")?.GetString(); var other = json.GetPropertyOrNull("other")?.GetStringDictionaryOrNull(); return new User { Id = id, Username = username, Email = email, IpAddress = ip, Segment = segment, _other = other?.WhereNotNullValue().ToDictionary() }; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.IO; using FastReport; using FastReport.Data; using IRAP.Global; using IRAP.Client.User; using IRAP.Client.Global.GUI.Dialogs; using IRAP.Entity.Kanban; using IRAP.Entities.MDM; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.MDM { public partial class frmTemplateManager : IRAP.Client.Global.frmCustomBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private AvailableSite currentTemplate = new AvailableSite(); private List<LeafSetEx> datas = new List<LeafSetEx>(); private string tempTemplateFile = string.Format( @"{0}Temp\temp.frx", AppDomain.CurrentDomain.BaseDirectory); private bool selectedChanged = false; private DateTime lastSelectedChangedTime = DateTime.Now; public frmTemplateManager(AvailableSite site) { InitializeComponent(); currentTemplate = site; string directory = Path.GetDirectoryName(tempTemplateFile); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); } private void CreateFRParameter( Report report, string paramName, string paramValue, string paramDesc) { if (report.Parameters.FindByName(paramName) == null) report.Parameters.Add( new Parameter(paramName) { Value = paramValue, Description = paramDesc, }); else report.Parameters.FindByName(paramName).Value = paramValue; } private void CreateFRParameter( Report report, string paramName, double paramValue, string paramDesc) { if (report.Parameters.FindByName(paramName) == null) report.Parameters.Add( new Parameter(paramName) { Value = paramValue, Description = paramDesc, }); else report.Parameters.FindByName(paramName).Value = paramValue; } private void SetReportParameters(Report report) { CreateFRParameter(report, "SendAddress", "上海浦东外高桥保税区华京路328号", "供货方地址"); CreateFRParameter(report, "CustomerCode", "123ABC456F", "客户代码"); CreateFRParameter(report, "CustomerName", "深圳市比亚迪供应链管理有限公司", "收货方名称"); CreateFRParameter(report, "ReceiveAddress", "NO.2 YADI RD, HIGH TXC. & ABCD", "收货方地址"); CreateFRParameter(report, "CustomerPartNumber", "3500310U2263", "客户零件号"); CreateFRParameter(report, "SupplierPartNumber", "18122405", "供应商零件号"); CreateFRParameter(report, "PartName", "前制动钳总成(左)", "零件名称"); CreateFRParameter(report, "Quantity", 150, "数量"); CreateFRParameter(report, "ContainerNo", "6OYK00427", "托盘号"); CreateFRParameter(report, "ProductDate", "2016年10月20日", "生产日期"); CreateFRParameter(report, "CustomerSN", "16B00002L211393500310U2263", "客户条码"); CreateFRParameter(report, "SupplierCode", "ABCD1234", "供应商代码"); } private string LoadTemplateFromDB(int t117LeafID) { string rlt = ""; string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; TemplateContent data = new TemplateContent(); IRAPMDMClient.Instance.ufn_GetInfo_TemplateFMTStr( IRAPUser.Instance.CommunityID, t117LeafID, IRAPUser.Instance.SysLogID, ref data, out errCode, out errText); WriteLog.Instance.WriteBeginSplitter(strProcedureName); if (errCode == 0) { rlt = data.TemplateFMTStr; } else { IRAPMessageBox.Instance.Show(errText, "获取标签模板", MessageBoxIcon.Error); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show(error.Message, "获取标签模板", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } return rlt; } private void GetTemplateList() { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { lstTemplates.Items.Clear(); int errCode = 0; string errText = ""; IRAPKBClient.Instance.sfn_AccessibleLeafSetEx( IRAPUser.Instance.CommunityID, 117, IRAPUser.Instance.ScenarioIndex, IRAPUser.Instance.SysLogID, ref datas, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { foreach (LeafSetEx data in datas) if (data.Code.ToUpper() == "FRX") lstTemplates.Items.Add(data); if (currentTemplate.T117LeafID != 0) { for (int i = 0; i < lstTemplates.Items.Count; i++) { if ((lstTemplates.Items[i] as LeafSetEx).LeafID == currentTemplate.T117LeafID) { lstTemplates.SelectedItem = lstTemplates.Items[i]; break; } } } } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void frmTemplateManager_Shown(object sender, EventArgs e) { lblCurrentTemplateName.Text = currentTemplate.T117Name; GetTemplateList(); } private void lstTemplates_SelectedIndexChanged(object sender, EventArgs e) { selectedChanged = true; lastSelectedChangedTime = DateTime.Now; } private void lblCurrentTemplateName_Click(object sender, EventArgs e) { if (currentTemplate.T117LeafID != 0) { string template = LoadTemplateFromDB(currentTemplate.T117LeafID); report.Clear(); report.LoadFromString(template); SetReportParameters(report); report.Preview = previewControl; if (report.Prepare()) { report.ShowPrepared(); previewControl.ZoomWholePage(); } } } private void contextMenuStrip_Opening(object sender, CancelEventArgs e) { if (lstTemplates.SelectedItem == null) e.Cancel = true; } private void tsmiReplace_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; IRAPMDMClient.Instance.usp_SaveFact_C75( IRAPUser.Instance.CommunityID, currentTemplate.CorrelationID, (lstTemplates.SelectedItem as LeafSetEx).LeafID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { Close(); } else { IRAPMessageBox.Instance.Show( errText, "系统信息", MessageBoxIcon.Error); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "系统信息", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void tsmiNew_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); if (File.Exists(tempTemplateFile)) File.Delete(tempTemplateFile); // 给新的标签模板取个名字 LeafSetEx data = lstTemplates.SelectedItem as LeafSetEx; string newTemplateName = GetString.Instance.Show( "给新的标签模板取个名", "请给新的标签模板设置一个名称:", data.LeafName); if (newTemplateName.Trim() == "") newTemplateName = "未取名的标签模板"; // 将当前的标签模板作为样本,新增新模板 report.Save(tempTemplateFile); report.FileName = tempTemplateFile; if (report.Design(true)) { report.Load(tempTemplateFile); string templateContext = report.SaveToString(); #region 保存修改后的模板内容 WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int newLeafID = 0; IRAPMDMClient.Instance.usp_SaveFact_IRAP117Node( IRAPUser.Instance.CommunityID, 117, "A", currentTemplate.T117LeafID, "FRX", "", newTemplateName, templateContext, IRAPUser.Instance.SysLogID, ref newLeafID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.Show( errText, "新增模板失败", MessageBoxIcon.Error); } else { GetTemplateList(); for (int i = 0; i < lstTemplates.Items.Count; i++) { LeafSetEx temp = lstTemplates.Items[i] as LeafSetEx; if (temp.LeafID == newLeafID) { lstTemplates.SelectedIndex = i; break; } } } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "系统信息", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } #endregion lstTemplates_SelectedIndexChanged(null, null); } } private void tsmiEdit_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); if (File.Exists(tempTemplateFile)) { File.Delete(tempTemplateFile); } // 将未修改前的模板保存到临时文件中 report.Save(tempTemplateFile); // 保存未修改前的模板内容,作为是否保存的依据 string oldTemplate = report.SaveToString(); report.FileName = tempTemplateFile; if (report.Design(true)) { report.Load(tempTemplateFile); string newTemplate = report.SaveToString(); #region 保存修改后的模板内容 WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int newLeafID = 0; LeafSetEx data = lstTemplates.SelectedItem as LeafSetEx; IRAPMDMClient.Instance.usp_SaveFact_IRAP117Node( IRAPUser.Instance.CommunityID, 117, "U", data.LeafID, "FRX", "", data.LeafName, newTemplate, IRAPUser.Instance.SysLogID, ref newLeafID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.Show( errText, "保存模板失败", MessageBoxIcon.Error); report.LoadFromString(oldTemplate); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "系统信息", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } #endregion lstTemplates_SelectedIndexChanged(null, null); } } private void tsmiDelete_Click(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); if (IRAPMessageBox.Instance.Show( "是否要删除当前选择的标签模板?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int newLeafID = 0; IRAPMDMClient.Instance.usp_SaveFact_IRAP117Node( IRAPUser.Instance.CommunityID, 117, "D", (lstTemplates.SelectedItem as LeafSetEx).LeafID, "", "", "", "", IRAPUser.Instance.SysLogID, ref newLeafID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.Show(errText, "系统信息", MessageBoxIcon.Error); } else { GetTemplateList(); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "系统信息", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } private void tsmiRename_Click(object sender, EventArgs e) { if (lstTemplates.SelectedItem == null) { return; } LeafSetEx data = lstTemplates.SelectedItem as LeafSetEx; // 给标签模板取个名字 string newTemplateName = GetString.Instance.Show( "重命名", string.Format( "您想将标签模板[{0}]更换成:", data.LeafName), data.LeafName); if (newTemplateName.Trim() != "") { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); #region 保存修改后的模板内容 WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int newLeafID = 0; IRAPMDMClient.Instance.usp_SaveFact_IRAP117Node( IRAPUser.Instance.CommunityID, 117, "U", data.LeafID, "FRX", "", newTemplateName, report.SaveToString(), IRAPUser.Instance.SysLogID, ref newLeafID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.Show( errText, "重命名失败", MessageBoxIcon.Error); } else { data.LeafName = newTemplateName; } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.Show( error.Message, "系统信息", MessageBoxIcon.Error); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } #endregion } } private void tmrShowLabelTemplate_Tick(object sender, EventArgs e) { if (selectedChanged) { TimeSpan span = DateTime.Now - lastSelectedChangedTime; if (span.TotalSeconds >= 0.5) { selectedChanged = false; if (lstTemplates.SelectedItem == null) { report.Preview = null; previewControl.Clear(); return; } LeafSetEx item = lstTemplates.SelectedItem as LeafSetEx; if (item.LeafID != 0) { string template = LoadTemplateFromDB(item.LeafID); report.Clear(); report.LoadFromString(template); SetReportParameters(report); report.Preview = previewControl; if (report.Prepare()) { report.ShowPrepared(); previewControl.ZoomWholePage(); } } } } } } }
using Uintra.Infrastructure.Providers; namespace Uintra.Features.CentralFeed.Links { public static class CentralFeedLinkProviderHelper { public static string GetFeedActivitiesAlias(IDocumentTypeAliasProvider aliasProvider) => aliasProvider.GetHomePage(); } }
/** * \file UIMenu.cs * \author Ab-code: Becky Linyan Li, Bowen Zhuang, Sekou Gassama, Tuan Ly * \date 11-21-2014 * \brief contains the user interfaces of the UIMenu class and methods to invoke other class libraries */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using AllEmployees; using TheCompany; using Supporting; namespace Presentation { /// /// \class UIMenu /// \brief This class provides a front-end interface to the rest of the class libraries. /// \brief Gathers user inputs and invokes the necessary methods to meet commands. /// public class UIMenu { /* ====================================== */ /* Private */ /* ====================================== */ /* -------------- ATTRIBUTES ------------ */ private ConsoleKeyInfo ckInfo; private Container cContainer = new Container(); private Logging logger = new Logging(); /* * METHOD : MenuRun * DESCRIPTION : This function calculates tax on a retail purchase in Ontario. * PARAMETERS : double purchaseAmount : untaxed amount * double hstTaxRate : HST tax rate * double pstTaxRate : Provincial tax rate * * RETURNS : double : total tax amount (includes HST and Provincial sales tax) * or a value of -1.00 on error */ /* ====================================== */ /* PUBLIC */ /* ====================================== */ /* -------------- METHODS ------------ */ /// /// \brief This method controls the flow of processes based on user input /// \brief by providing appropriate textual user-interfaces. /// \details <b>Details</b> - The user selects options that are laid out in menus. This method /// performs the input's actions while providing a robust user interface /// to navigate through the system's functionalities. /// \param none /// \return none /// public void MenuRun() { bool bQuit = false; //These four integers variables hold the return // value of each menu to process the option selected. int nRetMMenu = 0, nRetFMMenu = 0, nRetEMMenu = 0, nRetEDMenu = 0; while (!bQuit) { //Open main menu by default, unless flagged to open Manage Employees menu (3). nRetMMenu = MainMenu(); switch (nRetMMenu) { //Manage EMS DBase files (Menu 2). case 1: nRetFMMenu = FileManagementMenu(); switch (nRetFMMenu) { //Load EMS DBase from file. case 1: LoadDBase(); break; //Save Employee Set to EMS DBase file. case 2: SaveDBase(); break; //Return to Main Menu. case 9: continue; } break; //Manage Employees (Menu 3), re-iterate into else statement. case 2: nRetEMMenu = EmployeeManagementMenu(); switch (nRetEMMenu) { //Display Employee Set. case 1: DisplayEmployeeSet(); continue; //Create a NEW Employee (Opens Menu 4). case 2: CreateEmployee(1); continue; //Modify an EXISTING Employee (Opens Menu 4). case 3: ModifyEmployee(); continue; //Remove an EXISTING Employee (Opens Menu 4). case 4: RemoveEmployee(); continue; //Return to Main Menu case 9: continue; } continue; //Quit. case 9: bQuit = true; break; } } //When running .exe, these lines prevent the window from closing automatically. Console.WriteLine("{Session Complete}\nPress any key to close."); Console.ReadKey(); Console.Clear(); } /// /// \brief This method produces a menu of options and returns a valid input choice. /// \details <b>Details</b> - MAIN MENU: Options are to manage the database files or manage employees. /// Both options produce to a new menu. /// \param none /// \return Int32.Parse(ckInfo.KeyChar.ToString()) - <b>int</b> - integer representation of keystroke input /// public int MainMenu() { int nBreak = 0; while (nBreak == 0) { Console.WriteLine("Menu 1 : MAIN MENU"); Console.WriteLine("------------------"); Console.WriteLine(" 1. Manage EMS DBase files"); // goes to Menu 2 Console.WriteLine(" 2. Manage Employees"); // goes to menu 3 Console.WriteLine(" 9. Quit"); ckInfo = Console.ReadKey(); Console.Clear(); Console.Write("{0} was read. ", ckInfo.KeyChar); switch (ckInfo.KeyChar) { case '1': nBreak = 1; break; case '2': nBreak = 1; break; case '9': nBreak = 1; break; default: Console.WriteLine("Invalid input, please try again.\n"); break; } } Console.Clear(); return Int32.Parse(ckInfo.KeyChar.ToString()); } /// /// \brief This method produces a menu of options and returns a valid input choice. /// \details <b>Details</b> - FILE MANAGEMENT MENU: To load or to save a database from or to a file. /// Uses the Supporting class library to perform load/saves. /// LoadDBase & SaveDBase methods used to perform input. /// \param none /// \return Int32.Parse(ckInfo.KeyChar.ToString()) - <b>int</b> - integer representation of keystroke input /// public int FileManagementMenu() { int nBreak = 0; while (nBreak == 0) { Console.WriteLine("Menu 2 : FILE MANAGEMENT MENU"); Console.WriteLine("-----------------------------"); Console.WriteLine(" 1. Load EMS DBase from file"); Console.WriteLine(" 2. Save Employee Set to EMS DBase file"); Console.WriteLine(" 9. Return to Main Menu"); // back to Menu 1 ckInfo = Console.ReadKey(); Console.Clear(); Console.Write("{0} was read. ", ckInfo.KeyChar); switch (ckInfo.KeyChar) { case '1': nBreak = 1; break; case '2': nBreak = 1; break; case '9': nBreak = 1; break; default: Console.WriteLine("Invalid input, please try again.\n"); break; } } Console.Clear(); return Int32.Parse(ckInfo.KeyChar.ToString()); } /// /// \brief This method produces a menu of options and returns a valid input choice. /// \details <b>Details</b> - EMPLOYEE MANAGEMENT MENU: View employee database, create new employee, modify/remove existing employee. /// Viewing employee database traverses the container and uses the Details method to output information. /// CreateEmployee is used to handle prompts for employee attributes required to build an employee. /// Modify & Remove an existing employee uses the Container's search method to select and modify/remove employee. /// \param none /// \return Int32.Parse(ckInfo.KeyChar.ToString()) - <b>int</b> - integer representation of keystroke input /// public int EmployeeManagementMenu() { int nBreak = 0; while (nBreak == 0) { Console.WriteLine("Menu 3 : EMPLOYEE MANAGEMENT MENU"); Console.WriteLine("-----------------------------"); Console.WriteLine(" 1. Display Employee Set"); Console.WriteLine(" 2. Create a NEW Employee"); // goes to Menu 4 Console.WriteLine(" 3. Modify an EXISTING Employee (SIN required)"); // goes to Menu 4 Console.WriteLine(" 4. Remove an EXISTING Employee (SIN required)"); Console.WriteLine(" 9. Return to Main Menu"); // back to Menu 1 ckInfo = Console.ReadKey(); Console.Clear(); Console.Write("{0} was read. ", ckInfo.KeyChar); switch (ckInfo.KeyChar) { case '1': nBreak = 1; break; case '2': nBreak = 1; break; case '3': nBreak = 1; break; case '4': nBreak = 1; break; case '9': nBreak = 1; break; default: Console.WriteLine("Invalid input, please try again.\n"); break; } } Console.Clear(); return Int32.Parse(ckInfo.KeyChar.ToString()); } /// /// \brief This method produces a menu of options and returns a valid input choice. /// \details <b>Details</b> - EMPLOYEE DETAILS MENU: CREATE or MODIFY an existing employee, based on employee TYPE. /// CreateEmployee uses this return value to acquire employee class attributes. /// ModifyEmployee uses this return value to modify the employee type. /// \param none /// \return Int32.Parse(ckInfo.KeyChar.ToString()) - <b>int</b> - integer representation of keystroke input /// public int EmployeeDetailsMenu() { int nBreak = 0; while (nBreak == 0) { Console.WriteLine("Menu 4 : EMPLOYEE DETAILS MENU"); Console.WriteLine("-----------------------------"); Console.WriteLine(" 1. Specify Base Employee Details"); Console.WriteLine(" 2. Specify Full Time Employee Details"); Console.WriteLine(" 3. Specify Part Time Employee Details"); Console.WriteLine(" 4. Specify Contract Employee Details"); Console.WriteLine(" 5. Specify Seasonal Employee Details"); Console.WriteLine(" 9. Return to Main Menu"); // back to Menu 1 ckInfo = Console.ReadKey(); Console.Clear(); Console.Write("{0} was read. ", ckInfo.KeyChar); switch (ckInfo.KeyChar) { case '1': nBreak = 1; break; case '2': nBreak = 1; break; case '3': nBreak = 1; break; case '4': nBreak = 1; break; case '5': nBreak = 1; break; case '9': nBreak = 1; break; default: Console.WriteLine("Invalid input, please try again.\n"); break; } } Console.Clear(); return Int32.Parse(ckInfo.KeyChar.ToString()); } /// /// \brief This method creates a new employee and prompts user for attribute values. /// \details <b>Details</b> - Employee class validates all inputs through its setter methods. /// This method simply collects information and forwards it to the /// employee class. Once employee creation is complete, add to database. /// \param nEmployeeType - <b>int</b> - Value passed in to determine which EmployeeType is required /// \return none /// public void CreateEmployee(int nEmployeeType) { bool isTypeAcquired = false; string lastName = "", firstName = "", socialInsuranceNumber = "", dateOfBirth = ""; bool isOver = false; FulltimeEmployee f = new FulltimeEmployee(); ParttimeEmployee p = new ParttimeEmployee(); ContractEmployee c = new ContractEmployee(); SeasonalEmployee s = new SeasonalEmployee(); Employee tempEmployeeValidate = new Employee(); int quitCounter = 0; // nEmployeeType = EmployeeDetailsMenu(); if (nEmployeeType != 9) { //For Base Employee Details option, acquiring employee type is critical. if (nEmployeeType == 1) { while (!isTypeAcquired) { Console.WriteLine("Press between 1 to 4 to select employee type."); Console.WriteLine(" 1. Specify Full Time Employee Details"); Console.WriteLine(" 2. Specify Part Time Employee Details"); Console.WriteLine(" 3. Specify Contract Employee Details"); Console.WriteLine(" 4. Specify Seasonal Employee Details"); ckInfo = Console.ReadKey(); Console.Clear(); Console.Write("{0} was read. ", ckInfo.KeyChar); switch (ckInfo.KeyChar) { case '1': isTypeAcquired = true; f.SetemployeeType('F'); Console.WriteLine("Full time Employee type acquired.\n"); break; case '2': isTypeAcquired = true; p.SetemployeeType('P'); Console.WriteLine("Part time Employee type acquired.\n"); break; case '3': isTypeAcquired = true; c.SetemployeeType('C'); Console.WriteLine("Contract Employee type acquired.\n"); break; case '4': isTypeAcquired = true; s.SetemployeeType('S'); Console.WriteLine("Seasonal Employee type acquired.\n"); break; default: Console.WriteLine("Invalid input, please try again.\n"); break; } } nEmployeeType += Int32.Parse(ckInfo.KeyChar.ToString()); //This synchronizes Menu 4's return value to the 1-4 option here } while (!isOver) { Console.WriteLine("Please enter a non-blank last name/corporation name \n(valid characters: a-z, A-Z, ', -): "); lastName = Console.ReadLine(); if (tempEmployeeValidate.SetlastName(lastName)) { if (lastName != "") { Console.WriteLine("Last name accepted [{0}].\n", lastName); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "Employee set last name return false. Value:" + lastName, false); Console.WriteLine("Invalid characters found in last name: [{0}].\n", lastName); } //Ask for first name if not contract employee if (nEmployeeType != 4) { while (!isOver) { Console.WriteLine("Please enter a non-blank first name \n(valid characters: a-z, A-Z, ', -): "); firstName = Console.ReadLine(); if (tempEmployeeValidate.SetfirstName(firstName)) { if (firstName != "") { Console.WriteLine("First name accepted [{0}].\n", firstName); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "Employee set first name return false. Value:" + firstName, false); Console.WriteLine("Invalid characters found in last name: [{0}].\n", firstName); } while (!isOver) { Console.WriteLine("Please enter date of birth (YYYY-MM-DD): "); dateOfBirth = Console.ReadLine(); if (tempEmployeeValidate.SetdateOfBirth(dateOfBirth)) { if (dateOfBirth != "" && dateOfBirth != "N/A") { Console.WriteLine("Date of birth accepted [{0}].\n", dateOfBirth); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "Employee set date of birth return false. Value:" + dateOfBirth, false); Console.WriteLine("Must be in form of YYYY-MM-DD, \nwhere Y, M, and D each represent a digit: [{0}].\n", dateOfBirth); } quitCounter = 0; while (!isOver) { Console.WriteLine("Please enter Social Insurance Number (9 consecutive digits): "); socialInsuranceNumber = Console.ReadLine(); if (tempEmployeeValidate.SetsocialInsuranceNumber(socialInsuranceNumber)) { if (tempEmployeeValidate.validateSIN()) { Console.WriteLine("SIN accepted [{0}].\n", socialInsuranceNumber); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "Employee social insurance number return false. Value:" + socialInsuranceNumber, false); Console.WriteLine("Must be 9 consecutive digits & a valid Canadian SIN [{0}].\n", socialInsuranceNumber); quitCounter++; if (quitCounter > 2) { if (EndInputs()) { isOver = true; break; } } } } //Gather remaining attributes specific to employee children //Full time employee if (nEmployeeType == 2) { string hire = "", termination = ""; float salary = 0; quitCounter = 0; while (!isOver) { Console.WriteLine("Please enter employee hire date (YYYY-MM-DD): "); hire = Console.ReadLine(); if (f.SetdateOfHire(hire)) { if (hire != "" && hire != "N/A") { Console.WriteLine("Date of hire accepted [{0}].\n", hire); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "FullTimeEmployee set hire date return false. Value:" + hire, false); Console.WriteLine("Must be in form of YYYY-MM-DD, where Y, M, and D each represent a digit): [{0}].\n", hire); quitCounter++; if (quitCounter > 2) { if (EndInputs()) { isOver = true; break; } } } while (!isOver) { Console.WriteLine("Please enter employee termination date \n(YYYY-MM-DD, blank, N/A): "); termination = Console.ReadLine(); if (f.SetdateOfTermination(termination)) { Console.WriteLine("Date of termination accepted [{0}].\n", termination); break; } logger.Log("UIMenu", "CreateEmployee(int)", "FullTimeEmployee set termination date return false. Value:" + termination, false); Console.WriteLine("Must be in form of YYYY-MM-DD, \nwhere Y, M, and D each represent a digit (or blank, N/A): [{0}].\n", termination); } while (!isOver) { Console.WriteLine("Please enter employee salary (numeric, greater than 0): "); //If parsing float fails, salary remains less than 0 if (!float.TryParse(Console.ReadLine(), out salary)) { salary = -1; } if (f.Setsalary(salary)) { Console.WriteLine("Salary accepted [{0}].\n", salary); break; } logger.Log("UIMenu", "CreateEmployee(int)", "FullTimeEmployee set salary return false. Value:" + salary, false); Console.WriteLine("Salary must be numeric, non-zero, and non-negative : [{0}].\n", salary); } if (!isOver) { //Add remaining fields f.SetlastName(lastName); f.SetfirstName(firstName); f.SetsocialInsuranceNumber(socialInsuranceNumber); f.SetdateOfBirth(dateOfBirth); try { if (f.Validate()) { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + f.GetfirstName() + "-" + f.GetlastName() + " SIN: " + f.GetsocialInsuranceNumber(), true); if (cContainer.add(f)) { Console.WriteLine("Employee successfully added! Press any key to continue..."); } else { Console.WriteLine("Fail to add employee, the SIN number already exists. \nPress any key to continue..."); } Console.ReadKey(); Console.Clear(); } else { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + f.GetfirstName() + "-" + f.GetlastName() + " SIN: " + f.GetsocialInsuranceNumber(), false); Console.WriteLine("Employee is not valid. Save failed. Press any key to continue..."); Console.ReadKey(); Console.Clear(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } //Part time employee else if (nEmployeeType == 3) { string hire = "", termination = ""; float hourlyRate = 0; quitCounter = 0; while (!isOver) { Console.WriteLine("Please enter employee hire date (YYYY-MM-DD): "); hire = Console.ReadLine(); if (p.SetdateOfHire(hire)) { if (hire != "" && hire != "N/A") { Console.WriteLine("Date of hire accepted [{0}].\n", hire); break; } } Console.WriteLine("Must be in form of YYYY-MM-DD, \nwhere Y, M, and D each represent a digit: [{0}].\n", hire); quitCounter++; if (quitCounter > 2) { if (EndInputs()) { isOver = true; break; } } } while (!isOver) { Console.WriteLine("Please enter employee termination date (YYYY-MM-DD, blank, or N/A): "); termination = Console.ReadLine(); if (p.SetdateOfTermination(termination)) { Console.WriteLine("Date of termination accepted [{0}].\n", termination); break; } Console.WriteLine("Must be in form of YYYY-MM-DD, where \nY, M, and D each represent a digit (or blank, N/A): [{0}].\n", termination); } while (!isOver) { Console.WriteLine("Please enter employee hourlyRate (numeric, greater than 0): "); //If parsing float fails, salary remains 0 if (!float.TryParse(Console.ReadLine(), out hourlyRate)) { hourlyRate = -1; } if (p.SethourlyRate(hourlyRate)) { Console.WriteLine("hourlyRate accepted [{0}].\n", hourlyRate); break; } Console.WriteLine("hourlyRate must be numeric, non-zero, and non-negative : [{0}].\n", hourlyRate); } if (!isOver) { //Add remaining fields p.SetlastName(lastName); p.SetfirstName(firstName); p.SetsocialInsuranceNumber(socialInsuranceNumber); p.SetdateOfBirth(dateOfBirth); try { if (p.Validate()) { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + p.GetfirstName() + "-" + p.GetlastName() + " SIN: " + p.GetsocialInsuranceNumber(), true); if (cContainer.add(p)) { Console.WriteLine("Employee successfully added! Press any key to continue..."); } else { Console.WriteLine("Fail to add employee, the SIN number already exists. \nPress any key to continue..."); } Console.ReadKey(); Console.Clear(); } else { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + p.GetfirstName() + "-" + p.GetlastName() + " SIN: " + p.GetsocialInsuranceNumber(), false); Console.WriteLine("Employee is not valid. Save failed. Press any key to continue..."); Console.ReadKey(); Console.Clear(); } } catch(Exception e) { Console.WriteLine("Failed to add employee: " + e.Message); } } } //Contract time employee else if (nEmployeeType == 4) { string start = "", stop = ""; float amount = 0; //Add remaining fields c.SetlastName(lastName); c.SetdateOfBirth(dateOfBirth); //Temp amount for validate() to pass at current stage in "input order" c.SetfixedContractAmount(1); quitCounter = 0; while (!isOver) { while (!isOver) { Console.WriteLine("Please enter date of incorporation (YYYY-MM-DD): "); dateOfBirth = Console.ReadLine(); if (tempEmployeeValidate.SetdateOfBirth(dateOfBirth)) { if (dateOfBirth != "" && dateOfBirth != "N/A") { Console.WriteLine("Date of incorporation accepted [{0}].\n", dateOfBirth); break; } } logger.Log("UIMenu", "CreateEmployee(int)", "Employee set date of incorporation return false. Value:" + dateOfBirth, false); Console.WriteLine("Must be in form of YYYY-MM-DD,\nwhere Y, M, and D each represent a digit: [{0}].\n", dateOfBirth); } while (!isOver) { Console.WriteLine("Please enter Business Number (9 consecutive digits): "); socialInsuranceNumber = Console.ReadLine(); if (c.SetsocialInsuranceNumber(socialInsuranceNumber)) { Console.WriteLine("Business Number accepted [{0}].\n", socialInsuranceNumber); break; } logger.Log("UIMenu", "CreateEmployee(int)", "Employee business number return false. Value:" + socialInsuranceNumber, false); Console.WriteLine("Must be 9 consecutive digits: [{0}].\n", socialInsuranceNumber); quitCounter++; if (quitCounter > 2) { if (EndInputs()) { isOver = true; break; } } } if (!c.validateSIN()) { Console.WriteLine("WARNING: Business Number or Date of incorporation do not match [{0}].\n", socialInsuranceNumber); continue; } break; } quitCounter = 0; while (!isOver) { while (!isOver) { Console.WriteLine("Please enter contract start date (YYYY-MM-DD): "); start = Console.ReadLine(); if (c.SetcontractStartDate(start)) { if (start != "" || start != "N/A") { Console.WriteLine("contract start date accepted [{0}].\n", start); break; } } Console.WriteLine("Must be in form of YYYY-MM-DD, \nwhere Y, M, and D each represent a digit: [{0}].\n", start); quitCounter++; if (quitCounter > 4) { if (EndInputs()) { isOver = true; } } } while (!isOver) { Console.WriteLine("Please enter contract stop date (YYYY-MM-DD): "); stop = Console.ReadLine(); if (c.SetcontractStopDate(stop)) { if (stop != "" || stop != "N/A") { Console.WriteLine("Contract stop date accepted [{0}].\n", stop); break; } } Console.WriteLine("Must be in form of YYYY-MM-DD, \nwhere Y, M, and D each represent a digit: [{0}].\n", stop); quitCounter++; if (quitCounter > 4) { if (EndInputs()) { isOver = true; break; } } } if (!isOver) { try { c.Validate(); Console.WriteLine("Both contract start and end dates are valid.\n"); break; } catch (Exception e) { Console.WriteLine(e.Message); } quitCounter++; if (quitCounter > 4) { if (EndInputs()) { isOver = true; } } } } quitCounter = 0; while (!isOver) { Console.WriteLine("Please enter fixed contract amount(numeric, non-negative): "); //If parsing float fails, salary remains 0 if (!float.TryParse(Console.ReadLine(), out amount)) { amount = 0; } if (c.SetfixedContractAmount(amount)) { Console.WriteLine("Amount accepted [{0}].\n", amount); break; } Console.WriteLine("Amount must be numeric, non-zero, and non-negative : [{0}].\n", amount); } if (!isOver) { try { if (c.Validate()) { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + c.GetfirstName() + "-" + c.GetlastName() + " SIN: " + c.GetsocialInsuranceNumber(), true); if (cContainer.add(c)) { Console.WriteLine("Employee successfully added! Press any key to continue..."); } else { Console.WriteLine("Fail to add employee, the SIN/BN number already exists. \nPress any key to continue..."); } Console.ReadKey(); Console.Clear(); } else { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + c.GetfirstName() + "-" + c.GetlastName() + " SIN: " + c.GetsocialInsuranceNumber(), false); Console.WriteLine("Employee is not valid. Save failed. Press any key to continue..."); Console.ReadKey(); Console.Clear(); } } catch(Exception e) { Console.WriteLine("Failed to add employee: " + e.Message); } } } //Seasonal time employee else if (nEmployeeType == 5) { //Add remaining fields s.SetlastName(lastName); s.SetfirstName(firstName); s.SetsocialInsuranceNumber(socialInsuranceNumber); s.SetdateOfBirth(dateOfBirth); string season = ""; float piecePay = 0; quitCounter = 0; while (!isOver) { Console.WriteLine("Please enter the season (one of WINTER SPRING SUMMER FALL): "); season = Console.ReadLine(); if (s.Setseason(season)) { if (season != "") { Console.WriteLine("Season accepted [{0}].\n", season); break; } } Console.WriteLine("Only winter, spring, summer, or fall are valid inputs \n(non case-sensitive): [{0}].\n", season); quitCounter++; if (quitCounter > 2) { if (EndInputs()) { isOver = true; break; } } } while (!isOver) { Console.WriteLine("Please enter piece pay amount (numeric, non-negative): "); //If parsing float fails, salary remains 0 if (!float.TryParse(Console.ReadLine(), out piecePay)) { piecePay = 0; } if (s.SetpiecePay(piecePay)) { Console.WriteLine("Amount accepted [{0}].\n", piecePay); break; } Console.WriteLine("Amount must be numeric, non-zero, and non-negative : [{0}].\n", piecePay); } if (!isOver) { try { if (s.Validate()) { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + s.GetfirstName() + "-" + s.GetlastName() + " SIN: " + s.GetsocialInsuranceNumber(), true); if (cContainer.add(s)) { Console.WriteLine("Employee successfully added! Press any key to continue..."); } else { Console.WriteLine("Fail to add employee, the SIN number has already exists. \nPress any key to continue..."); } Console.ReadKey(); Console.Clear(); } else { logger.Log("UIMenu", "CreateEmployee(int)", "Validate " + s.GetfirstName() + "-" + s.GetlastName() + " SIN: " + s.GetsocialInsuranceNumber(), false); Console.WriteLine("Employee is not valid. Save failed. \nPress any key to continue..."); Console.ReadKey(); Console.Clear(); } } catch(Exception e) { Console.WriteLine("Failed to add employee: " + e.Message); } } } } } /// /// \brief This method uses the Supporting class library to load a database from file. /// \details <b>Details</b> - The FileIO class contains methods to open and read the database /// from file. These will be invoked and the database will be saved /// into the cContainer attribute above. /// \param none /// \return none /// public void LoadDBase() { try { bool result = cContainer.loadData(); if (!result) { Console.WriteLine("Load data failed.\n"); } else { Console.WriteLine("Load data successfully.\n"); } } catch (Exception e) { Console.WriteLine("Error: Load Data failed. " + e.Message + "\n"); } } /// /// \brief This method uses the Supporting class library to save a database into a file. /// \details <b>Details</b> - The FileIO class contains methods to write and save a database to /// a file. These will be invoked and cContainer database will be saved /// into a file. /// \param none /// \return none /// public void SaveDBase() { try { bool result = cContainer.saveData(); if (!result) { Console.WriteLine("Save data failed.\n"); } else { Console.WriteLine("Save data successfully.\n"); } } catch (Exception e) { Console.WriteLine("error: Save Data failed. " + e.Message + "\n"); } } /// /// \brief This method displays all employees within the database (valid and invalid). /// \details <b>Details</b> - Employees will be displayed along with their full attributes, /// one employee at a time through the database list. The Details /// method is used from the AllEmployee class. /// \param none /// \return none /// public void DisplayEmployeeSet() { try { cContainer.traverseEmployee(); Console.WriteLine(); } catch (Exception e) { Console.WriteLine("Display all employee failed. " + e.Message); } } /// /// \brief This method will modify an existing employee /// \details <b>Details</b> - User is prompt for a specific employee type to modify. /// If employee exists, proceed to modify the employee. /// \param none /// \return none /// public void ModifyEmployee() { bool isloop = true; Employee employee = null; Employee cEmployee = null; while (isloop) { Console.WriteLine("Please enter the SIN of the employee you want to modify. \n(press Enter key to go back to main menu.)"); string sin = Console.ReadLine(); string sinToBN = ""; sin.Replace("\n", ""); if (sin.Trim() == "") { isloop = false; Console.Clear(); Console.WriteLine("Enter pressed. Returning to Main Menu ...\n"); break; } //remove all unwanted characters and add space for format sin = Regex.Replace(sin, "[^0-9]", ""); if (sin.Length == 9) { sinToBN = sin.Insert(5, " "); sin = sin.Insert(3, " "); sin = sin.Insert(7, " "); } else { Console.WriteLine("The employee with the SIN " + sin + " does not exist.\n"); continue; } employee = cContainer.search(sin); cEmployee = cContainer.search(sinToBN); if ((employee == null) && (cEmployee == null)) { Console.WriteLine("The employee with the SIN " + sin + " does not exist.\n"); continue; } else { if (employee == null) { employee = cEmployee; } employee.Details(); logger.Log("UIMenu", "ModifyEmployee", "Employee detail is called:\n " + employee.ToString(), true); char eType = employee.GetemployeeType(); switch (eType) { case Employee.FULL_TIME: modifyFullTimeEmployee(ref employee); break; case Employee.PART_TIME: modifyPartTimeEmployee(ref employee); break; case Employee.CONTRACT: modifyContractEmployee(ref employee); break; case Employee.SEASONAL: modifySeasonaleEmployee(ref employee); break; } } } } /// /// \brief This method will modify an employee considering it as a base class /// \details <b>Details</b> - modiy fist name, last name,date of birth. SIN and type of employee can not be modified /// \param ref Employee employee /// \return none /// private void modifyEmployee(ref Employee employee) { bool isLoop = true; if (employee.GetemployeeType() != Employee.CONTRACT) { while (isLoop) { Console.WriteLine("Please enter the first name (valid characters: a-z, A-Z, ', -): "); string name = Console.ReadLine(); if (employee.SetfirstName(name)) { if (name != "") { isLoop = false; } } else { Console.WriteLine("First Name is not valid.\n"); logger.Log("UIMenu", "modifyEmployee(ref Employee employee)", "Employee set first name return false. Value:" + name, false); } } //last Name isLoop = true; while (isLoop) { Console.WriteLine("Please enter the last name (valid characters: a-z, A-Z, ', -): "); string name = Console.ReadLine(); if (employee.SetlastName(name)) { if (name != "") { isLoop = false; } } else { Console.WriteLine("Last Name is not valid.\n"); logger.Log("UIMenu", "modifyEmployee(ref Employee employee)", "Employee set last name return false. Value:" + name, false); } } isLoop = true; //dateOfBirth while (isLoop) { Console.WriteLine("Please enter date of birth (YYYY-MM-DD): "); string date = Console.ReadLine(); if (employee.SetdateOfBirth(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { Console.WriteLine("Date of birth is not valid.\n"); logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set date of birth return false. Value:" + date, false); } } } else { isLoop = true; while (isLoop) { Console.WriteLine("Please enter the company name (valid characters: a-z, A-Z, ', -): "); string name = Console.ReadLine(); if (employee.SetlastName(name)) { if (name != "") { isLoop = false; } } else { Console.WriteLine("Company Name is not valid.\n"); logger.Log("UIMenu", "modifyEmployee(ref Employee employee)", "Employee set last name return false. Value:" + name, false); } } } } /// /// \brief This method will modify an fulltime employee /// \details <b>Details</b> - it first copy the value to a new fulltime employee object, then pass the object to container. If the object is valid then modify successd /// \param ref Employee employee /// \return none /// private void modifyFullTimeEmployee(ref Employee employee) { FulltimeEmployee femployee = (FulltimeEmployee)employee; FulltimeEmployee newEmployee = new FulltimeEmployee(); if (!newEmployee.SetfirstName(femployee.GetfirstName())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set first name return false. Value:" + femployee.GetfirstName(), false); } if (!newEmployee.SetlastName(femployee.GetlastName())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set last name return false. Value:" + femployee.GetlastName(), false); } if (!newEmployee.SetdateOfHire(femployee.GetdateOfHire())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set date of hire return false. Value:" + femployee.GetdateOfHire(), false); } if (!newEmployee.SetdateOfTermination(femployee.GetdateOfTermination())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set date of termination return false. Value:" + femployee.GetdateOfTermination(), false); } if (!newEmployee.SetdateOfBirth(femployee.GetdateOfBirth())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set date of birth return false. Value:" + femployee.GetdateOfBirth(), false); } if (!newEmployee.SetsocialInsuranceNumber(femployee.GetsocialInsuranceNumber())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set social Insurance Number return false. Value:" + femployee.GetsocialInsuranceNumber(), false); } if (!newEmployee.Setsalary(femployee.Getsalary())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set social Salary return false. Value:" + femployee.Getsalary(), false); } if (!newEmployee.SetemployeeType(femployee.GetemployeeType())) { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set social Salary return false. Value:" + femployee.GetemployeeType(), false); } Employee tempEmployee = newEmployee; this.modifyEmployee(ref tempEmployee); //hire date bool isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee hire date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetdateOfHire(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set data of hire return false. Value:" + date, false); Console.WriteLine("Employee hire date is not valid.\n"); } } //termation date isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee termination date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetdateOfTermination(date)) { isLoop = false; } else { Console.WriteLine("Employee termination date is not valid.\n"); logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set termination date return false. Value:" + date, false); } } // salary isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee salary (numeric, non-negative): "); string salarystr = Console.ReadLine(); try { float salary = float.Parse(salarystr); if (newEmployee.Setsalary(salary)) { isLoop = false; } else { Console.WriteLine("Employee salary is not valid.\n"); logger.Log("UIMenu", "modifyFullTimeEmployee", "Employee set salary return false. Value:" + salary, false); } } catch (Exception e) { Console.WriteLine("Employee salary is not valid:\n" + e.Message + "\n"); } } try { cContainer.modify(newEmployee); Console.WriteLine("Modify employee successfully. \n"); } catch (Exception e) { Console.WriteLine("Modify employee failed: \n" + e.Message + "\n"); } } /// /// \brief This method will modify a parttime employee /// \details <b>Details</b> - it first copy the value to a new fulltime employee object, then pass the object to container. If the object is valid then modify successd /// \param ref Employee employee /// \return none /// private void modifyPartTimeEmployee(ref Employee employee) { ParttimeEmployee femployee = (ParttimeEmployee)employee; ParttimeEmployee newEmployee = new ParttimeEmployee(); if (!newEmployee.SetfirstName(femployee.GetfirstName())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set first name return false. Value:" + femployee.GetfirstName(), false); } if (!newEmployee.SetlastName(femployee.GetlastName())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set last name return false. Value:" + femployee.GetlastName(), false); } if (!newEmployee.SetdateOfHire(femployee.GetdateOfHire())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set date of hire return false. Value:" + femployee.GetdateOfHire(), false); } if (!newEmployee.SetdateOfTermination(femployee.GetdateOfTermination())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set date of termination return false. Value:" + femployee.GetdateOfTermination(), false); } if (!newEmployee.SetdateOfBirth(femployee.GetdateOfBirth())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set date of birth return false. Value:" + femployee.GetdateOfBirth(), false); } if (!newEmployee.SetsocialInsuranceNumber(femployee.GetsocialInsuranceNumber())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set social Insurance Number return false. Value:" + femployee.GetsocialInsuranceNumber(), false); } if (!newEmployee.SetemployeeType(femployee.GetemployeeType())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set social Salary return false. Value:" + femployee.GetemployeeType(), false); } if (!newEmployee.SethourlyRate(femployee.GethourlyRate())) { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set hourly rate return false. Value:" + femployee.GethourlyRate(), false); } Employee tempEmployee = newEmployee; this.modifyEmployee(ref tempEmployee); //hire date bool isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee hire date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetdateOfHire(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set date of hire return false. Value:" + date, false); Console.WriteLine("Employee hire date is not valid.\n"); } } //termation date isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee termination date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetdateOfTermination(date)) { isLoop = false; } else { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set date of termination return false. Value:" + date, false); Console.WriteLine("Employee termination date is not valid.\n"); } } // salary isLoop = true; while (isLoop) { Console.WriteLine("Please enter employee hourly rate (numeric, non-negative): "); string salarystr = Console.ReadLine(); try { float salary = float.Parse(salarystr); if (newEmployee.SethourlyRate(salary)) { isLoop = false; } else { logger.Log("UIMenu", "modifyPartTimeEmployee", "Employee set hourly rate return false. Value:" + salarystr, false); Console.WriteLine("Employee hourly rate is not valid.\n"); } } catch (Exception e) { Console.WriteLine("Employee hourly rate is not valid:\n" + e.Message +"\n"); } } try { cContainer.modify(newEmployee); Console.WriteLine("Modify Employee successfully.\n"); } catch (Exception e) { Console.WriteLine("Modify Employee failed:\n" + e.Message + "\n"); } } /// /// \brief This method will modify a contract employee /// \details <b>Details</b> - it first copy the value to a new fulltime employee object, then pass the object to container. If the object is valid then modify successd /// \param ref Employee employee /// \return none /// private void modifyContractEmployee(ref Employee employee) { ContractEmployee femployee = (ContractEmployee)employee; ContractEmployee newEmployee = new ContractEmployee(); if (!newEmployee.SetfirstName(femployee.GetfirstName())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set first name return false. Value:" + femployee.GetfirstName(), false); } if (!newEmployee.SetlastName(femployee.GetlastName())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set last name return false. Value:" + femployee.GetlastName(), false); } if (!newEmployee.SetdateOfBirth(femployee.GetdateOfBirth())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set date of birth return false. Value:" + femployee.GetdateOfBirth(), false); } if (!newEmployee.SetsocialInsuranceNumber(femployee.GetsocialInsuranceNumber())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set social Insurance Number return false. Value:" + femployee.GetsocialInsuranceNumber(), false); } if (!newEmployee.SetemployeeType(femployee.GetemployeeType())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set social Salary return false. Value:" + femployee.GetemployeeType(), false); } if (!newEmployee.SetfixedContractAmount(femployee.GetfixedContractAmount())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set social Salary return false. Value:" + femployee.GetfixedContractAmount(), false); } if (!newEmployee.SetcontractStartDate(femployee.GetcontractStartDate())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set contract start date return false. Value:" + femployee.GetcontractStartDate(), false); } if (!newEmployee.SetcontractStopDate(femployee.GetcontractStopDate())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set contract stop date return false. Value:" + femployee.GetcontractStopDate(), false); } Employee tempEmployee = newEmployee; this.modifyEmployee(ref tempEmployee); //contract start date bool isLoop = true; while(true) { while (isLoop) { Console.WriteLine("\nPlease enter contract start date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetcontractStartDate(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { logger.Log("UIMenu", "modifyContractEmployee", "Employee set contract start date return false. Value:" + date, false); Console.WriteLine("Contract start date is not valid.\n"); } } //termation date isLoop = true; while (isLoop) { Console.WriteLine("Please enter contract stop date (YYY-MM-DD): "); string date = Console.ReadLine(); if (newEmployee.SetcontractStopDate(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { logger.Log("UIMenu", "modifyContractEmployee", "Employee set contract stop date return false. Value:" + date, false); Console.WriteLine("Contract termination date is not valid.\n"); } } try { bool isValid = newEmployee.Validate(); logger.Log("UIMenu", "modifyContractEmployee", "Validate " + employee.GetfirstName() + "-" + employee.GetlastName() + " SIN: " + employee.GetsocialInsuranceNumber(), isValid); Console.WriteLine("Contract start and termination dates are valid.\n"); break; } catch(Exception e) { logger.Log("UIMenu", "modifyContractEmployee", "Validate " + employee.GetfirstName() + "-" + employee.GetlastName() + " SIN: " + employee.GetsocialInsuranceNumber(), false); Console.WriteLine(e.Message + "\n"); } } // salary isLoop = true; while (isLoop) { Console.WriteLine("Please enter fixed contract amount(numeric, non-negative): "); string salarystr = Console.ReadLine(); try { float salary = float.Parse(salarystr); if (newEmployee.SetfixedContractAmount(salary)) { isLoop = false; } else { Console.WriteLine("Contract amount is not valid.\n"); logger.Log("UIMenu", "modifyContractEmployee", "Employee set contract amount return false. Value:" + salarystr, false); } } catch (Exception e) { Console.WriteLine("Contract amount is not valid: \n" + e.Message + "\n"); } } try { cContainer.modify(newEmployee); Console.WriteLine("Modify Employee successfully.\n"); } catch (Exception e) { Console.WriteLine("Modify Employee failed:\n" + e.Message + "\n"); } } /// /// \brief This method will modify an seasonal employee /// \details <b>Details</b> - it first copy the value to a new fulltime employee object, then pass the object to container. If the object is valid then modify successd /// \param ref Employee employee /// \return none /// private void modifySeasonaleEmployee(ref Employee employee) { SeasonalEmployee femployee = (SeasonalEmployee)employee; SeasonalEmployee newEmployee = new SeasonalEmployee(); if (!newEmployee.SetfirstName(femployee.GetfirstName())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set first name return false. Value:" + femployee.GetfirstName(), false); } if (!newEmployee.SetlastName(femployee.GetlastName())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set last name return false. Value:" + femployee.GetlastName(), false); } if (!newEmployee.SetdateOfBirth(femployee.GetdateOfBirth())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set date of birth return false. Value:" + femployee.GetdateOfBirth(), false); } if (!newEmployee.SetsocialInsuranceNumber(femployee.GetsocialInsuranceNumber())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set social Insurance Number return false. Value:" + femployee.GetsocialInsuranceNumber(), false); } if (!newEmployee.SetemployeeType(femployee.GetemployeeType())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set employee type return false. Value:" + femployee.GetemployeeType(), false); } if (!newEmployee.SetpiecePay(femployee.GetpiecePay())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set piece pay return false. Value:" + femployee.GetpiecePay(), false); } if (!newEmployee.Setseason(femployee.Getseason())) { logger.Log("UIMenu", "modifyContractEmployee", "Employee set season return false. Value:" + femployee.Getseason(), false); } Employee tempEmployee = newEmployee; this.modifyEmployee(ref tempEmployee); bool isLoop = true; while (isLoop) { Console.WriteLine("Please enter the season (case insensitive: WINTER SPRING SUMMER FALL): "); string date = Console.ReadLine(); if (newEmployee.Setseason(date)) { if (date != "N/A" && date != "") { isLoop = false; } } else { Console.WriteLine("Season is not valid.\n"); logger.Log("UIMenu", "modifyContractEmployee", "Employee set season return false. Value:" + date, false); } } isLoop = true; while (isLoop) { Console.WriteLine("Please enter piece pay amount (numeric, non-negative): "); float salary; if (float.TryParse(Console.ReadLine(), out salary)) { if (newEmployee.SetpiecePay(salary)) { isLoop = false; } else { logger.Log("UIMenu", "modifyContractEmployee", "Employee set piece pay return false. Value:" + salary, false); Console.WriteLine("Piece pay amout is not valid.\n"); } } else { Console.WriteLine("Piece pay amout is not valid.\n"); } } try { cContainer.modify(newEmployee); Console.WriteLine("Modify Employee successfully.\n" ); } catch (Exception e) { Console.WriteLine("ModifyEmployee failed: \n" + e.Message + "\n"); } } /// /// \brief This method will remove an existing employee found by a social insurance number. /// \details <b>Details</b> - The Container class found in TheCompany class library provides /// a method to search for an employee given a SIN. Once found, /// user is prompt to confirm removal of employee. /// \param none /// \return none /// public void RemoveEmployee() { bool isloop = true; Employee employee = null; Employee cEmployee = null; //search employee by sin first while (isloop) { Console.WriteLine("Please enter the SIN of the employee you want to remove. \n(press Enter key to go back to main menu.)"); string sin = Console.ReadLine(); string sinToBN = ""; sin.Replace("\n", ""); if (sin.Trim() == "") { return; } //remove all unwanted characters and add space for format sin = Regex.Replace(sin, "[^0-9]", ""); if (sin.Length == 9) { sinToBN = sin.Insert(5, " "); sin = sin.Insert(3, " "); sin = sin.Insert(7, " "); } else { Console.WriteLine("The employee with the SIN " + sin + " does not exist.\n"); continue; } employee = cContainer.search(sin); cEmployee = cContainer.search(sinToBN); if ( (employee == null) && (cEmployee==null) ) { Console.WriteLine("Employee with SIN " + sin + " does not exist. \nDo you want to delete another employee? If so, enter Y."); string answer = Console.ReadLine(); if (answer.ToUpper() != "Y") { isloop = false; } } else { //display the employee if (employee == null) { employee = cEmployee; } employee.Details(); logger.Log("UIMenu", "RemoveEmployee", "Employee detail is called:\n " + employee.ToString(), true); Console.WriteLine("Do you realy want to delete this employee? If so, enter Y."); string answer = Console.ReadLine(); if (answer.ToUpper() != "Y") { continue; } else { isloop = false; } } } //if employee is not null delete it try { if (employee != null) { bool result = cContainer.remove(employee); if (result) { Console.WriteLine("Delete employee successfully.\n"); } } } catch (Exception e) { Console.WriteLine("Delete employee failed:\n" + e.Message + "\n"); } } /// /// \brief This method produces a menu of options and returns a valid input choice. /// \details <b>Details</b> - EMPLOYEE MANAGEMENT MENU: View employee database, create new employee, modify/remove existing employee. /// Viewing employee database traverses the container and uses the Details method to output information. /// CreateEmployee is used to handle prompts for employee attributes required to build an employee. /// Modify & Remove an existing employee uses the Container's search method to select and modify/remove employee. /// \param none /// \return Int32.Parse(ckInfo.KeyChar.ToString()) - <b>int</b> - integer representation of keystroke input /// public bool EndInputs() { Console.WriteLine("[You seem to be having trouble.]\n[Return to main menu?]\n[If so, press 1.]\n"); ckInfo = Console.ReadKey(); Console.WriteLine(); if (ckInfo.KeyChar == '1') { Console.Clear(); Console.WriteLine("1 Pressed. Returning to Main Menu... \n"); return true; } return false; } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace RU.Tinkoff.Acquiring.Sdk { // Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='DefaultKeyCreator']" [global::Android.Runtime.Register ("ru/tinkoff/acquiring/sdk/DefaultKeyCreator", DoNotGenerateAcw=true)] public partial class DefaultKeyCreator : global::Java.Lang.Object, global::RU.Tinkoff.Acquiring.Sdk.IKeyCreator { internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("ru/tinkoff/acquiring/sdk/DefaultKeyCreator", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DefaultKeyCreator); } } protected DefaultKeyCreator (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Landroid_content_Context_; // Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='DefaultKeyCreator']/constructor[@name='DefaultKeyCreator' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register (".ctor", "(Landroid/content/Context;)V", "")] public unsafe DefaultKeyCreator (global::Android.Content.Context p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (((object) this).GetType () != typeof (DefaultKeyCreator)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "(Landroid/content/Context;)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "(Landroid/content/Context;)V", __args); return; } if (id_ctor_Landroid_content_Context_ == IntPtr.Zero) id_ctor_Landroid_content_Context_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Landroid/content/Context;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Landroid_content_Context_, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor_Landroid_content_Context_, __args); } finally { } } static Delegate cb_create; #pragma warning disable 0169 static Delegate GetCreateHandler () { if (cb_create == null) cb_create = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Create); return cb_create; } static IntPtr n_Create (IntPtr jnienv, IntPtr native__this) { global::RU.Tinkoff.Acquiring.Sdk.DefaultKeyCreator __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.DefaultKeyCreator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.Create ()); } #pragma warning restore 0169 static IntPtr id_create; // Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='DefaultKeyCreator']/method[@name='create' and count(parameter)=0]" [Register ("create", "()Ljava/security/PublicKey;", "GetCreateHandler")] public virtual unsafe global::Java.Security.IPublicKey Create () { if (id_create == IntPtr.Zero) id_create = JNIEnv.GetMethodID (class_ref, "create", "()Ljava/security/PublicKey;"); try { if (((object) this).GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Java.Security.IPublicKey> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_create), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Java.Security.IPublicKey> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "create", "()Ljava/security/PublicKey;")), JniHandleOwnership.TransferLocalRef); } finally { } } } }
using BenchmarkDotNet.Attributes; using Sentry.Extensibility; using Sentry.Protocol.Envelopes; using BackgroundWorker = Sentry.Internal.BackgroundWorker; namespace Sentry.Benchmarks; public class BackgroundWorkerFlushBenchmarks { private class FakeTransport : ITransport { public Task SendEnvelopeAsync(Envelope envelope, CancellationToken cancellationToken = default) => Task.CompletedTask; } private IBackgroundWorker _backgroundWorker; private SentryEvent _event; private Envelope _envelope; [IterationSetup] public void IterationSetup() { _backgroundWorker = new BackgroundWorker(new FakeTransport(), new SentryOptions { MaxQueueItems = 1000 }); _event = new SentryEvent(); _envelope = Envelope.FromEvent(_event); // Make sure worker spins once. _backgroundWorker.EnqueueEnvelope(_envelope); _backgroundWorker.FlushAsync(TimeSpan.FromSeconds(10)).GetAwaiter().GetResult(); for (var i = 0; i < Items; i++) { _backgroundWorker.EnqueueEnvelope(_envelope); } } [Params(1, 10, 100, 1000)] public int Items; [Benchmark(Description = "Enqueue event and FlushAsync")] public Task FlushAsync_QueueDepthAsync() => _backgroundWorker.FlushAsync(TimeSpan.FromSeconds(10)); }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base; using System; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual { /// <summary> /// Representa el objeto request del contrato /// </summary> /// <remarks> /// Creación : GMD 20150528 <br /> /// Modificación : <br /> /// </remarks> public class ContratoEstadioConsultaRequest : Filtro { /// <summary> /// Codigo de Contrato Estadio Consulta /// </summary> public Guid? CodigoContratoEstadioConsulta { get; set; } /// <summary> /// Codigo Contrato de Estadio /// </summary> public Guid CodigoContratoEstadio { get; set; } /// <summary> /// Descripcion /// </summary> public string Descripcion { get; set; } /// <summary> /// Fecha de Registro /// </summary> public DateTime FechaRegistro { get; set; } /// <summary> /// Codigo de Parrafo /// </summary> public Guid? CodigoContratoParrafo { get; set; } /// <summary> /// Destinatario /// </summary> public Guid Destinatario { get; set; } /// <summary> /// Respuesta /// </summary> public string Respuesta { get; set; } /// <summary> /// Fecha de Respuesta /// </summary> public DateTime FechaRespuesta { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AI.Neurons; namespace AI { [Serializable] [System.Runtime.Serialization.DataContract] public class Layer { [System.Runtime.Serialization.DataMember] private Neuron[] neurons; [System.Runtime.Serialization.DataMember] public int Inputs { get; set; } [System.Runtime.Serialization.DataMember] public double[] Output { get; set; } [System.Runtime.Serialization.IgnoreDataMember] public int Size { get { return neurons.Length; } } public Layer(int inputsCount, int neuronsCount, Functions.IActivationFunction function, INeuronInitilizer initializer) { Inputs = inputsCount; neurons = new Neuron[neuronsCount]; for(int i = 0; i < neuronsCount; ++i) { neurons[i] = new Neuron(inputsCount, function, initializer); } Output = new double[neuronsCount]; } public void Initialize() { foreach(Neuron neuron in neurons) neuron.Initialize(); } public double[] CalculateOutput(double[] input) { for (int i = 0; i < neurons.Length; ++i) Output[i] = neurons[i].ComputeOutput(input); return Output; } public Neuron this[int i] { get { return neurons[i]; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Business.OnlinePay.Company.ChinaPay { public abstract class ResponseBase { /// <summary> /// 应答名称 /// </summary> public abstract string ResponseName { get ; } /// <summary> /// 版本号 /// </summary> [FieldIndex(1)] public string Ver { get; set; } /// <summary> /// 数字交易码 /// </summary> [FieldIndex(2)] public string TransCode { get; set; } /// <summary> /// 商户代码 /// </summary> [FieldIndex(3)] public string MerId { get; set; } /// <summary> /// 请求日期 /// </summary> [FieldIndex(4)] public string SrcReqDate { get; set; } /// <summary> /// 请求流水号 /// </summary> [FieldIndex(5)] public string SrcReqId { get; set; } /// <summary> /// 渠道号 /// </summary> [FieldIndex(6)] public string ChannelId { get; set; } /// <summary> /// 交易结果 /// </summary> [FieldIndex(7)] public string RespCode { get; set; } /// <summary> /// 结果描述 /// </summary> [FieldIndex(8)] public string RespMsg { get; set; } /// <summary> /// 签名 /// </summary> [FieldIndex(9)] public string Signature { get; set; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace CliqueLib { public class CliqueLib { public static List<List<T>> CliquesToStrategies<T>(List<List<int>> cliques, T[] seq) where T : IInput { List<List<T>> res = new List<List<T>>(); foreach (var cliq in cliques) { List<T> resLine = new List<T>(); foreach(var v in cliq) { resLine.Add(seq[v]); } res.Add(resLine); } return res; } public static List<List<T>> GraphToStrategies<T>(List<List<int>> comp, T[] seq) where T : IInput { List<List<T>> res = new List<List<T>>(); for (int i = 0; i < comp.Count; i++) { List<T> resLine = new List<T>(); for (int j = 0; j < comp[i].Count; j++) { resLine.Add(seq[comp[i][j]]); } res.Add(resLine); } return res; } public static List<List<T>> CreateComponents<T>(T[] seq) where T : IInput { List<List<T>> ComponentsList = new List<List<T>>(); Graph g = new Graph(seq.Length); //isWeaker //проверять, если один сильнее другого, то for (int i = 0; i < seq.Length; i++) { for (int j = i + 1; j < seq.Length; j++) { bool checkInc = (seq[i].CheckInconsistency(seq[j])); if (checkInc) { g.addEdgeUndir(i, j); } } //bool? isWeaker = seq[i].IsWeaker(seq[j]); } return GraphToStrategies(g.connectedComponents(), seq); } public static List<List<T>> CreateStrongComponents<T>(T[] seq) where T : IInput { List<List<T>> ComponentsList = new List<List<T>>(); Graph g = new Graph(seq.Length); //isWeaker //проверять, если один сильнее другого, то for (int i = 0; i < seq.Length; i++) { for (int j = i + 1; j < seq.Length; j++) { bool checkInc = (seq[i].CheckInconsistency(seq[j])); if (checkInc) { g.addEdgeDir(i, j); } } } return GraphToStrategies(g.stronglyConnectedComponents(), seq); } public static List<List<T>> GreedySetCover<T>(T[] seq) where T : IInput { return null; } public static List<List<T>> PowerSetCover<T>(T[] seq) where T : IInput { return null; } public static List<T> MaxCliqueToStrategies<T>(int[] clique, T[] seq) where T : IInput { List<T> maxClique = new List<T>(); for (int i = 0; i < clique.Length; i++) { if (clique[i] == 1) { maxClique.Add(seq[i]); } } return maxClique; } public static List<T> MaxClique<T>(T[] seq) where T : IInput { Graph g = new Graph(seq.Length); for (int i = 0; i < seq.Length; i++) { for (int j = i + 1; j < seq.Length; j++) { bool checkInc = (seq[i].CheckInconsistency(seq[j])); if (checkInc) { g.addEdgeUndir(i, j); } } } g.search(); int[] clique = g.solution; return MaxCliqueToStrategies(clique, seq); } public static List<List<int>> BronKerbosch(HashSet<int>[] AdjListArray, List<List<int>> cliques, HashSet<int> remainingNodes, HashSet<int> potentialClique, HashSet<int> skipNodes) { //Console.WriteLine("1 potential clique [{0}]", String.Join(",", potentialClique)); //Console.WriteLine("1 remaining nodes [{0}]", String.Join(",", remainingNodes)); //Console.WriteLine("1 skip nodes [{0}]", String.Join(",", skipNodes)); if (remainingNodes.Count == 0 & skipNodes.Count == 0) { List<int> copyClique = new List<int>(potentialClique); copyClique.Sort(); cliques.Add(copyClique); return null; } while(remainingNodes.Any()) { int v = remainingNodes.First(); //Console.WriteLine(v); HashSet<int> newPotentialClique = potentialClique; newPotentialClique.Add(v); //Console.WriteLine("2 potential clique [{0}]", String.Join(",", newPotentialClique)); HashSet<int> newRemainingNodes = new HashSet<int>(remainingNodes.Where(X => AdjListArray[v].Contains(X))); //Console.WriteLine("2 remaining nodes [{0}]", String.Join(",", newRemainingNodes)); HashSet<int> newSkipNodes = new HashSet<int>(skipNodes.Where(X => AdjListArray[v].Contains(X))); //Console.WriteLine("2 skip nodes [{0}]", String.Join(",", newSkipNodes)); BronKerbosch(AdjListArray, cliques, newRemainingNodes, newPotentialClique, newSkipNodes); remainingNodes.Remove(v); //нужно менять еще и remaining nodes skipNodes.Add(v); potentialClique.Clear(); } cliques = cliques.OrderByDescending(arr => arr.Count).ToList(); return cliques; } public static List<List<T>> AllCliques<T>(T[]seq) where T : IInput { Graph g = new Graph(seq.Length); for (int i = 0; i < seq.Length; i++) { for (int j = i + 1; j < seq.Length; j++) { bool checkInc = (seq[i].CheckInconsistency(seq[j])); if (checkInc) { g.addEdgeUndir(i, j); } } } HashSet<int> skipNodes = new HashSet<int>(); HashSet<int> potentialClique = new HashSet<int>(); HashSet<int> remainingNodes = new HashSet<int>(); List<List<int>> cliques = new List<List<int>>(); for(int i = 0; i<seq.Length; i++) { remainingNodes.Add(i); } List<List<int>> BronKerboschCliques = BronKerbosch(g.adjListArray, cliques, remainingNodes, potentialClique, skipNodes); return CliquesToStrategies(BronKerboschCliques, seq); } } }
namespace MySurveys.Web.Areas.Administration.Controllers { using System.Collections; using System.Web.Mvc; using Kendo.Mvc.UI; using MvcTemplate.Web.Infrastructure.Mapping; using Services.Contracts; using ViewModels; public class PossibleAnswersController : AdminController { private IPossibleAnswerService possibleAnswers; public PossibleAnswersController(IUserService userService, IPossibleAnswerService possibleAnswers) : base(userService) { this.possibleAnswers = possibleAnswers; } //// GET: Administration/PossibleAnswers public ActionResult Index() { return this.View(); } [HttpPost] public ActionResult Update([DataSourceRequest]DataSourceRequest request, PossibleAnswerViewModel model) { if (model != null && this.ModelState.IsValid) { var dbModel = this.possibleAnswers.GetById(model.Id); var mapped = this.Mapper.Map(model, dbModel); this.possibleAnswers.Update(mapped); } return this.GridOperation(model, request); } [HttpPost] public ActionResult Destroy([DataSourceRequest]DataSourceRequest request, PossibleAnswerViewModel model) { base.Destroy<PossibleAnswerViewModel>(request, model, model.Id); return this.GridOperation(model, request); } protected override IEnumerable GetData() { return this.possibleAnswers .GetAll() .To<PossibleAnswerViewModel>(); } protected override void Delete<T>(object id) { this.possibleAnswers.Delete(id); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeveredDoor : MonoBehaviour { public bool isOpen; public Sprite openedDoor; public Sprite closedDoor; // Use this for initialization void Start () { //The door can start either opened or closed depending on the bool value we set in the inspector. if (isOpen) GetComponent<SpriteRenderer>().sprite = openedDoor; else GetComponent<SpriteRenderer>().sprite = closedDoor; } //Closed the door if it's open, open it if it's closed. public void openClose() { if ( isOpen ) { GetComponent<SpriteRenderer>().sprite = closedDoor; isOpen = false; } else { GetComponent<SpriteRenderer>().sprite = openedDoor; isOpen = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BusinessObjects; using DataAccess.IRepository; namespace DataAccess.Repository { public class CommentLikeRepository: ICommentLikeRepository { public CommentLike GetCommentLike(string username, int commentId) => CommentLikeDAO.Instance.GetCommentLike(username, commentId); public void AddCommentLike(CommentLike like) => CommentLikeDAO.Instance.AddCommentLike(like); public void DeleteLike(string username, int postId) => CommentLikeDAO.Instance.DeleteLike(username, postId); public CommentLike CheckCommentLike(string username, int commentId) => CommentLikeDAO.Instance.CheckCommentLike(username, commentId); public IEnumerable<CommentLike> GetCommentLikeByCommentId(int commentId) => CommentLikeDAO.Instance.GetCommentLikeByCommentId(commentId); } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; public delegate void CallBackObjPool(); /// <summary> /// /// </summary> public class ObjectPool { private Type m_destType = null; private object[] m_ctorArgs = null; private int m_minObjCount = 0; private int m_maxObjCount = 0; private int m_idleObjCount = 0; private int m_shrinkPoint = 0; private Hashtable m_hashTableObjs = new Hashtable(); //private Hashtable m_hashTableStatus = new Hashtable(); private Dictionary<int, bool> m_hashTableStatus = new Dictionary<int,bool>(); //private ArrayList m_keyList = new ArrayList(); private QuickList<int> m_keyList = new QuickList<int>(); private bool m_supportReset = false; public event CallBackObjPool PoolShrinked; public event CallBackObjPool MemoryUseOut; /// <summary> /// 初始化对象池 /// </summary> /// <param name="objType">对象类型</param> /// <param name="cArgs">构造参数</param> /// <param name="minNum">最小值</param> /// <param name="maxNum">最大值</param> /// <returns></returns> public bool Initialize(Type objType, object[] cArgs, int minNum, int maxNum) { if (minNum < 1) minNum = 1; if (maxNum < 5) maxNum = 5; m_destType = objType; m_ctorArgs = cArgs; m_minObjCount = minNum; m_maxObjCount = maxNum; double cof = 1 - ((double)minNum / (double)maxNum); this.m_shrinkPoint = (int)(cof * minNum); this.m_idleObjCount = 0; Type supportType = typeof(IPooledObjSupporter); if (supportType.IsAssignableFrom(objType)) { this.m_supportReset = true; } //this.InstanceObjects(); return true; } /// <summary> /// 批量实例化对象 /// </summary> private void InstanceObjects() { for (int n = 0; n < m_minObjCount; ++n) { CreateOneObject(); } } /// <summary> /// 重置对象池 /// </summary> public void RestPool() { this.Shrink(); } /// <summary> /// 创建一个Object对象 /// </summary> /// <returns></returns> private int CreateOneObject() { object obj = null; try { obj = Activator.CreateInstance(m_destType, m_ctorArgs); } catch (Exception) { m_maxObjCount = CurrentObjCount; if (m_minObjCount > CurrentObjCount) m_minObjCount = CurrentObjCount; if (MemoryUseOut != null) MemoryUseOut(); return -1; } int key = obj.GetHashCode(); m_hashTableObjs.Add(key, obj); m_hashTableStatus.Add(key, true); m_keyList.Add(key); m_idleObjCount++; return key; } /// <summary> /// 销毁一个对象 /// </summary> /// <param name="key"></param> private void DestroyOneObject(int key) { object target = m_hashTableObjs[key]; IDisposable disposable = target as IDisposable; if (disposable != null) disposable.Dispose(); if (this.m_hashTableStatus[key]) { this.m_idleObjCount--; } m_hashTableObjs.Remove(key); m_hashTableStatus.Remove(key); m_keyList.Remove(key); } /// <summary> /// 获取一个Object /// </summary> /// <returns></returns> public object GetObject() { ObjectPool pool = this; lock (pool) { object target = null; int num = -1; int keysCount = m_keyList.Count; for (int n = 0; n < keysCount; ++n) { num = m_keyList[n]; if (m_hashTableStatus[num]) { m_hashTableStatus[num] = false; this.m_idleObjCount--; target = m_hashTableObjs[num]; break; } } if (target == null) { if (keysCount < m_maxObjCount) { num = this.CreateOneObject(); if (num != -1) { m_hashTableStatus[num] = false; this.m_idleObjCount--; target = m_hashTableObjs[num]; } } //else if(keysCount < m_maxObjCount * 1.5) //{ // num = this.CreateOneObject(); // if (num != -1) // { // m_hashTableStatus[num] = false; // this.m_idleObjCount--; // target = m_hashTableObjs[num]; // } // Debugging.LogError("Error:Object Pool Above MaxCout." + m_destType.ToString()); //} } return target; } } /// <summary> /// 将对象退回对象池 /// </summary> /// <param name="objHashCode"></param> public void GiveBackObject(int objHashCode) { if (!m_hashTableStatus.ContainsKey(objHashCode) || m_hashTableStatus[objHashCode]) return; ObjectPool pool = this; lock (pool) { if (m_hashTableStatus.ContainsKey(objHashCode) && !m_hashTableStatus[objHashCode]) { m_hashTableStatus[objHashCode] = true; m_idleObjCount++; if (m_supportReset) { try { IPooledObjSupporter supporter = (IPooledObjSupporter)m_hashTableObjs[objHashCode]; supporter.Reset(); } catch (Exception ex) { DebugLogger.LogException(ex); } } if (CanShrink()) Shrink(); } } } /// <summary> /// 是否通收缩 /// </summary> /// <returns></returns> private bool CanShrink() { int idleCount = GetIdleObjCount(); int busyCount = CurrentObjCount - idleCount; return (busyCount < m_shrinkPoint) && (this.CurrentObjCount > (this.MinObjCount + (this.MaxObjCount - this.MinObjCount) / 2)); } /// <summary> /// 检查对象状态 /// </summary> /// <param name="hashCode"></param> /// <returns></returns> public bool CheckObjectStatus(int hashCode) { if (!this.m_hashTableStatus.ContainsKey(hashCode)) { return false; } return this.m_hashTableStatus[hashCode]; } /// <summary> /// 收缩 /// </summary> private void Shrink() { int index = 0; while (index < this.m_keyList.m_size) { int key = this.m_keyList[index]; if (this.m_hashTableStatus[key]) { this.DestroyOneObject(key); } else { index++; } if (this.CurrentObjCount <= this.MinObjCount) { break; } } if (PoolShrinked != null) PoolShrinked(); } /// <summary> /// 销毁 /// </summary> public void Dispose() { Type supType = typeof(System.IDisposable); if (supType.IsAssignableFrom(m_destType)) { int num = this.m_keyList.Count - 1; for (int n = num; n >= 0; n--) { this.DestroyOneObject(this.m_keyList[n]); } //ArrayList list = (ArrayList)this.m_keyList.Clone(); //for (int n = 0; n < list.Count; ++n) //{ // this.DestroyOneObject((int)list[n]); //} } m_hashTableStatus.Clear(); m_hashTableObjs.Clear(); m_keyList.Clear(); } /// <summary> /// 最小对象数 /// </summary> public int MinObjCount { get{return m_minObjCount;} } /// <summary> /// 最大对象数 /// </summary> public int MaxObjCount { get{return m_maxObjCount;} } /// <summary> /// 当前对象数 /// </summary> public int CurrentObjCount { get{return m_keyList.Count;} } /// <summary> /// 空闲对象数 /// </summary> public int IdleObjCount { get { ObjectPool pool = this; lock (pool) { return this.GetIdleObjCount(); } } } /// <summary> /// 获取空闲对象数 /// </summary> /// <returns></returns> private int GetIdleObjCount() { return this.m_idleObjCount; //int count = 0; //for (int n = 0; n < m_keyList.Count; ++n) //{ // if (m_hashTableStatus[m_keyList[n]]) // ++count; //} //return count; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HW05.iOS; //using MonoTouch.Foundation; //using MonoTouch.UIKit; [assembly: Xamarin.Forms.Dependency(typeof(Who))] namespace HW05.iOS { public class Who : IWho { public string Hello() { return "iOSiOSiOS"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using LicenseObjects; namespace AxiEndPoint.EndPointServer.MessageHandlers { public class GetClientMessageHandler:IMessageHandler { private readonly ServerSettings _settings; public GetClientMessageHandler(ServerSettings settings) { _settings = settings; } private const string GET_CLIENT_COMMAND_TEXT = "GetClient"; public bool SatisfyBy(EndPointClient.Transfer.Message message) { return message.Command.CommandText.StartsWith(GET_CLIENT_COMMAND_TEXT); } public byte[] Handle(MessageEventArgs args) { string guid = ""; string hashcode = ""; string[] sa = args.Message.Command.CommandText.Split('^'); if (args.Message.Command.CommandText.StartsWith(GET_CLIENT_COMMAND_TEXT) && (sa.Count() > 1)) { guid=sa[1]; hashcode = sa[2]; } if (Loader.DataContext == null) Loader.DataContext = new FbDataConnection(_settings.ConnectionString); if (Loader.DataContext.CheckConnection()) { Client c = null; if (guid != "") c = Loader.DbLoadSingle<Client>(String.Format("guid='{0}'", guid)); else c = Loader.DbLoadSingle<Client>(String.Format("Upper(hashstring)='{0}'", hashcode)); string ipaddr = args.ClientIp.Substring(0, args.ClientIp.IndexOf(":")); Saver.DataContext = Loader.DataContext; Saver.SaveToDb<ClientActivity>(new ClientActivity() { Action = 0, IdClient = c.Id, IpAddress = ipaddr }); if (c.DateExpire <= DateTime.Now.AddDays(5)) if (c.IpAddress == ipaddr) { c.DateExpire = null; Saver.SaveToDb<Client>(c); c.Granted = false; } using (MemoryStream ms = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, c); AxiEndPoint.EndPointServer.Logging.Log.Debug(args.ClientIp + " Отправлен клиент " + c.Id); return ms.ToArray(); } } else return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // TODO: данная строка кода позволяет загрузить данные в таблицу "pHCdatabaseDataSet.PhysicalGrowth". При необходимости она может быть перемещена или удалена. this.physicalGrowthTableAdapter.Fill(this.pHCdatabaseDataSet.PhysicalGrowth); // TODO: данная строка кода позволяет загрузить данные в таблицу "pHCdatabaseDataSet.PhysicalFitness". При необходимости она может быть перемещена или удалена. this.physicalFitnessTableAdapter.Fill(this.pHCdatabaseDataSet.PhysicalFitness); // TODO: данная строка кода позволяет загрузить данные в таблицу "pHCdatabaseDataSet.FunctionalTraining". При необходимости она может быть перемещена или удалена. this.functionalTrainingTableAdapter.Fill(this.pHCdatabaseDataSet.FunctionalTraining); // TODO: данная строка кода позволяет загрузить данные в таблицу "pHCdatabaseDataSet.Athletes". При необходимости она может быть перемещена или удалена. this.athletesTableAdapter.Fill(this.pHCdatabaseDataSet.Athletes); } private void athletesToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView1.DataSource = athletesBindingSource; } private void functionalTrainingToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView1.DataSource = functionalTrainingBindingSource; } private void physicalFitnessToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView1.DataSource = physicalFitnessBindingSource; } private void physicalGrowthToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView1.DataSource = physicalGrowthBindingSource; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEvoscape.Components { public class Stats { #region Fields int strength; int stamina; int agility; int intellect; int wisdom; int education; #endregion #region Properties // TODO Make set fields? Do these need to be read-only? public int Strength { get { return strength; } } public int Stamina { get { return stamina; } } public int Agility { get { return agility; } } public int Intellect { get { return intellect; } } public int Wisdom { get { return wisdom; } } public int Eucation { get { return education; } } #endregion #region Constructors /// <summary> /// Makes a new Stats with the value given for every respectives stat. /// </summary> /// <param name="strength"></param> /// <param name="stamina"></param> /// <param name="agility"></param> /// <param name="intellect"></param> /// <param name="wisdom"></param> /// <param name="education"></param> public Stats(int strength, int stamina, int agility, int intellect, int wisdom, int education) { this.strength = strength; this.stamina = stamina; this.agility = agility; this.intellect = intellect; this.wisdom = wisdom; this.education = education; } /// <summary> /// Makes a new Stats with 0 for every stat. /// </summary> public Stats() { this.strength = 0; this.stamina = 0; this.agility = 0; this.intellect = 0; this.wisdom = 0; this.education = 0; } #endregion #region Methods // TODO Do we need any methods in Stats? I'm sure we do. // Presumably something like modifyStat() to unilaterally change a bunch of stats. #endregion } }
/* INFINITY CODE 2013-2018 */ /* http://www.infinity-code.com */ using UnityEngine; using UnityEngine.UI; namespace InfinityCode.OnlineMapsDemos { [AddComponentMenu("Infinity Code/Online Maps/Demos/Demo")] public class Demo : MonoBehaviour { public Text twoThreeDText; public Toggle labelsToggle; public Toggle trafficToggle; public Toggle elevationsToggle; public Transform camera2D; public Transform camera3D; public Shader tileShader; public float CameraChangeTime = 1; private GUIStyle activeRowStyle; private float animValue; private OnlineMaps map; private OnlineMapsTileSetControl control; private bool is2D = true; private bool isCameraModeChange; private GUIStyle rowStyle; private string search = ""; private OnlineMapsMarker searchMarker; private Transform fromTransform; private Transform toTransform; private bool preventDoubleWarning; public void ChangeMode() { if (isCameraModeChange) return; is2D = !is2D; twoThreeDText.text = is2D ? "3D" : "2D"; // elevationsToggle.gameObject.SetActive(!is2D); animValue = 0; isCameraModeChange = true; Camera c = Camera.main; fromTransform = is2D ? camera3D : camera2D; toTransform = is2D ? camera2D : camera3D; c.orthographic = false; if (!is2D) c.fieldOfView = 28; } public void SetLabels() { map.labels = labelsToggle.isOn; map.Redraw(); } public void SetTraffic() { map.traffic = trafficToggle.isOn; map.Redraw(); } public void SetElevations() { if (preventDoubleWarning) { preventDoubleWarning = false; return; } if (!OnlineMapsKeyManager.hasBingMaps || string.IsNullOrEmpty(control.bingAPI)) { Debug.LogWarning("Please enter Map / Key Manager / Bing Maps"); preventDoubleWarning = true; elevationsToggle.isOn = false; return; } control.useElevation = elevationsToggle.isOn; map.Redraw(); } private void OnFindLocationComplete(string result) { Vector2 position = OnlineMapsGoogleGeocoding.GetCoordinatesFromResult(result); if (position == Vector2.zero) return; if (searchMarker == null) searchMarker = map.AddMarker(position, search); else { searchMarker.position = position; searchMarker.label = search; } if (map.zoom < 13) map.zoom = 13; map.position = position; map.Redraw(); } private void Start() { map = OnlineMaps.instance; control = OnlineMapsTileSetControl.instance; } private void Update() { if (!isCameraModeChange) return; animValue += Time.deltaTime / CameraChangeTime; if (animValue > 1) { animValue = 1; isCameraModeChange = false; } Camera c = Camera.main; c.transform.position = Vector3.Lerp(fromTransform.position, toTransform.position, animValue); c.transform.rotation = Quaternion.Lerp(fromTransform.rotation, toTransform.rotation, animValue); float fromFOV = is2D ? 60 : 28; float toFOV = is2D ? 28 : 60; c.fieldOfView = Mathf.Lerp(fromFOV, toFOV, animValue); if (!isCameraModeChange && is2D) c.orthographic = true; } } }
namespace CustomerApp.UnitTests { using System; using System.Collections.Generic; using System.Globalization; using DataAccess; using DataAccess.Entities; using DataAccess.Models; using Dtos; using FluentAssertions; using NUnit.Framework; [TestFixture] public class DtoMapperTests { [TestCase(1, "some content")] [TestCase(5, "some other content")] [TestCase(12, null)] public void GiveNoteDetail_ThenNoteDetailDto_ContainsExpectedProperties(int id, string content) { var noteDetail = new NoteDetail{ Id = id, Content = content }; var noteDetailDto = noteDetail.ToDto(); noteDetailDto.Id.Should().Be(noteDetail.Id); noteDetailDto.Content.Should().Be(noteDetail.Content); } [TestCase(1, "some content")] [TestCase(5, "some other content")] [TestCase(12, null)] public void GiveNoteDetailDto_ThenNoteDetail_ContainsExpectedProperties(int id, string content) { var noteDetailDto = new NoteDetailDto { Id = id, Content = content }; var noteDetail = noteDetailDto.ToModel(); noteDetail.Id.Should().Be(noteDetail.Id); noteDetail.Content.Should().Be(noteDetail.Content); } [TestCase(1, "some content")] [TestCase(5, "some other content")] [TestCase(12, null)] public void GiveNewNoteDto_ThenNewNote_ContainsExpectedProperties(int id, string content) { var newNoteDto = new NewNoteDto { CustomerId = id, Content = content }; var newNote = newNoteDto.ToModel(); newNote.CustomerId.Should().Be(newNote.CustomerId); newNote.Content.Should().Be(newNote.Content); } [TestCase(1, "Jean", 1999)] [TestCase(5, "some other name", 1876)] [TestCase(12, null, 1956)] public void GivenCustomerDetail_ThenCustomerDetailDto_ContainsExpectedProperties(int id, string firstName, int year) { var customerDetail = new CustomerDetail { Id = id, Address = "Some Street", Created = new DateTime(year, 1, 1), FirstName = firstName, LastName = "Smith", Status = Status.Current, Email = $"{firstName}@smith.com" }; var customerDetailsDto = customerDetail.ToDto(); customerDetailsDto.Id.Should().Be(customerDetail.Id); customerDetailsDto.Address.Should().Be(customerDetail.Address); customerDetailsDto.Created.Should().Be(customerDetail.Created.ToString("O", CultureInfo.InvariantCulture)); customerDetailsDto.FirstName.Should().Be(customerDetail.FirstName); customerDetailsDto.LastName.Should().Be(customerDetail.LastName); customerDetailsDto.Status.Should().Be(customerDetail.Status.ToString()); customerDetailsDto.Email.Should().Be(customerDetail.Email); } [TestCase(1, "Jean", 1999)] [TestCase(5, "some other name", 1876)] [TestCase(12, null, 1956)] public void GivenCustomerDetailsDto_ThenCustomerDetails_ContainsExpectedProperties(int id, string firstName, int year) { var creationDate = new DateTime(year, 1, 1); const Status status = Status.Current; var customer = new CustomerDetailDto { Id = id, Address = "Some Street", Created = creationDate.ToString("O", CultureInfo.InvariantCulture), FirstName = firstName, LastName = "Smith", Status = status.ToString(), Email = $"{firstName}@smith.com" }; var customerDetails = customer.ToModel(); customerDetails.Id.Should().Be(customer.Id); customerDetails.Address.Should().Be(customer.Address); customerDetails.Created.Should().Be(creationDate); customerDetails.FirstName.Should().Be(customer.FirstName); customerDetails.LastName.Should().Be(customer.LastName); customerDetails.Status.Should().Be(status); customerDetails.Email.Should().Be(customer.Email); } [Test] public void WhenMappingDtoToModel_AndCreationDateCannotBeParsed_ThenExceptionThrown() { var customer = new CustomerDetailDto { Id = 1, Address = "Some Street", Created = "not a date", FirstName = "Liz", LastName = "Smith", Status = Status.Current.ToString(), Email = $"liz@smith.com" }; Action sut = () => customer.ToModel(); sut.Should().Throw<FormatException>(); } [Test] public void WhenMappingDtoToModel_AndStatusCannotBeParsed_ThenStatusIsProspective() { const string notAValidStatusString = "not a valid Status string"; var customer = new CustomerDetailDto { Id = 1, Address = "Some Street", Created = new DateTime(2010, 1, 1).ToString("O", CultureInfo.InvariantCulture), FirstName = "Liz", LastName = "Smith", Status = notAValidStatusString, Email = "liz@smith.com" }; customer.ToModel().Status.Should().Be(Status.Prospective); } [TestCase(1, "Jean")] [TestCase(5, "some other name")] [TestCase(12, null)] public void GivenCustomerSummary_ThenCustomerSummaryDto_ContainsExpectedProperties(int id, string firstName) { var customerSummary = new CustomerSummary { Id = id, FirstName = firstName, LastName = "Smith", Status = Status.Current, }; var customerSummaryDto = customerSummary.ToDto(); customerSummaryDto.Id.Should().Be(customerSummary.Id); customerSummaryDto.FirstName.Should().Be(customerSummary.FirstName); customerSummaryDto.LastName.Should().Be(customerSummary.LastName); customerSummaryDto.Status.Should().Be(customerSummary.Status.ToString()); } [TestCase(1, "Jean", 1999)] [TestCase(5, "some other name", 1876)] [TestCase(12, null, 1956)] public void GivenCustomerWithNotes_ThenCustomerDetails_ContainsExpectedProperties(int id, string firstName, int year) { var customer = new Customer { Id = id, Address = "Some Street", Created = new DateTime(year, 1, 1), FirstName = firstName, LastName = "Smith", Status = Status.Current, Email = "liz@smith.com", Notes = new List<Note> { new Note {Id = 1, Content = "Some note"}, new Note {Id = 2, Content = "2nd note"}, new Note {Id = 3, Content = "3rd note"}, new Note {Id = 4, Content = "4th note"} } }; var customerDetails = customer.ToModel(); customerDetails.Id.Should().Be(customer.Id); customerDetails.Address.Should().Be(customer.Address); customerDetails.Created.Should().Be(customer.Created); customerDetails.FirstName.Should().Be(customer.FirstName); customerDetails.LastName.Should().Be(customer.LastName); customerDetails.Status.Should().Be(customer.Status); customerDetails.Email.Should().Be(customer.Email); } } }
namespace mssngrrr.utils { public static class Log4NetExtension { public static string SafeToLog(this string line) { return line.Trim().Replace("\r", "\\r").Replace("\n", "\\n"); } } }
using UnityEngine; using System.Collections; public class HealthPowerup : Powerup { private float _healthBonusMultiplier; /// <summary> /// Initializes a new instance of the <see cref="HealthPowerup"/> class. /// </summary> /// <param name="name">Name.</param> /// <param name="description">Description.</param> /// <param name="sprite">Sprite.</param> /// <param name="available">If set to <c>true</c> powerup is available.</param> /// <param name="healthBonus">Health bonus.</param> public HealthPowerup(string name, string description, Sprite sprite, bool available, float healthBonus) : base(name, description, sprite, available) { _healthBonusMultiplier = healthBonus; } public override void Enabled () { PlayerProperties.inst.healthMultiplier += _healthBonusMultiplier; } }
using System; using System.Collections.Generic; using UnityEngine; public class RegionBehaviour : MonoBehaviour { public static RegionBehaviour RegionSelected; public static RegionBehaviour RegionLooking; public static List<RegionBehaviour> Regions = new List<RegionBehaviour>(); public Color GroundColor; public Color WaterColor; public GameObject Select; public Region Region; public delegate void RegionHandler(RegionBehaviour selectedRegion); private event RegionHandler OnRegionSelectedLMB; private event RegionHandler OnRegionSelectedRMB; private PopulationBehaviour populationBehaviour; public void Initialize() { Regions.Add(this); LoadRegion(); } void LoadRegion() { SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>(); populationBehaviour = GetComponentInChildren<PopulationBehaviour>(); MarginHandler marginHandler = GetComponentInChildren<MarginHandler>(); RiverHandler riverHandler = GetComponentInChildren<RiverHandler>(); switch (Region.Type) { case RegionType.Ground: spriteRenderer.color = Color.Lerp(Color.black, GroundColor, 1 - Region.Altitude); populationBehaviour.SetPopulation(Region.city.population.Density, Region.city.population.SymptomaticDensity); break; case RegionType.Coast: spriteRenderer.color = Color.Lerp(Color.black, GroundColor, 1 - Region.Altitude); marginHandler.SetMargin(Region, Color.Lerp(Color.black, WaterColor, Region.Altitude)); populationBehaviour.SetPopulation(Region.city.population.Density, Region.city.population.SymptomaticDensity); break; case RegionType.Water: spriteRenderer.color = Color.Lerp(Color.black, WaterColor, Region.Altitude); Destroy(populationBehaviour.gameObject); break; } GetComponentInChildren<DelimiterHandler>().SetDelimiter(Region); if (Region.River.exists) { riverHandler.SetRiver(Region, WaterColor); } } public bool BuildWall(int Position) { if (Region.Frontiers[Position].wall != null) { return false; } Region.BlockNeighborhood(Position); return true; } public void SubscribeOnInfected(Action subscriber) { if (Region != null && !Region.IsWater()) Region.RegionInfected += subscriber; } public static void SubscribeOnClickLMB(RegionHandler subscriber) { foreach (RegionBehaviour regionB in Regions) { regionB.OnRegionSelectedLMB += subscriber; } } public static void SubscribeOnClickRMB(RegionHandler subscriber) { foreach (RegionBehaviour regionB in Regions) { regionB.OnRegionSelectedRMB += subscriber; } } public void UpdateRegion() { if (populationBehaviour != null) populationBehaviour.SetPopulation(Region.city.population.Density, Region.city.population.SymptomaticDensity); } public void ShowPopulation(bool show) { if (!Region.IsWater()) populationBehaviour.gameObject.SetActive(show); } public void OnLMBUp() { if (RegionSelected == this) { RegionSelected = null; } RegionSelected = this; OnRegionSelectedLMB?.Invoke(this); } public void OnRMBUp() { OnRegionSelectedRMB?.Invoke(this); } private void OnMouseEnter() { if (Select != null) Select.SetActive(true); } private void OnMouseExit() { if (Select != null) Select.SetActive(false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using System.Threading.Tasks; using System.Net.Http.Headers; using System.IO; using Newtonsoft.Json; namespace Api.Controllers { public class UploadDataModel { public string testString1 { get; set; } public string testString2 { get; set; } } public class UploaderController : ApiController { // You could extract these two private methods to a separate utility class since // they do not really belong to a controller class but that is up to you private MultipartFormDataStreamProvider GetMultipartProvider() { // IMPORTANT: replace "(tilde)" with the real tilde character // (our editor doesn't allow it, so I just wrote "(tilde)" instead) var uploadFolder = "UploadFile"; // you could put this to web.config var root = HttpContext.Current.Server.MapPath(uploadFolder); Directory.CreateDirectory(root); return new MultipartFormDataStreamProvider(root); } // Extracts Request FormatData as a strongly typed model private object GetFormData<T>(MultipartFormDataStreamProvider result) { if (result.FormData.HasKeys()) { var unescapedFormData = Uri.UnescapeDataString(result.FormData .GetValues(0).FirstOrDefault() ?? String.Empty); if (!String.IsNullOrEmpty(unescapedFormData)) return JsonConvert.DeserializeObject<T>(unescapedFormData); } return null; } private string GetDeserializedFileName(MultipartFileData fileData) { var fileName = GetFileName(fileData); return JsonConvert.DeserializeObject(fileName).ToString(); } public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { public CustomMultipartFormDataStreamProvider(string path) : base(path) { } public override string GetLocalFileName(HttpContentHeaders headers) { return headers.ContentDisposition.FileName; } } public string GetFileName(MultipartFileData fileData) { return fileData.Headers.ContentDisposition.FileName; } [HttpPost] [Route("api/Upload")] public HttpResponseMessage UploadJsonFile() { HttpResponseMessage response = new HttpResponseMessage(); var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName); postedFile.SaveAs(filePath); } } return response; } } }
using System.Globalization; using NeuroLinker.Enumerations; namespace NeuroLinker.Helpers { /// <summary> /// Assist with creation of MAL urls /// </summary> public static class MalRouteBuilder { #region Public Methods /// <summary> /// Url for adding an anime to a user's list /// </summary> /// <param name="id">Id of anime to add</param> /// <returns>Anime add url</returns> public static string AddAnime(int id) => $"{Parts.Root}/{Parts.Api}/{Parts.AnimeList}/{Parts.Add}/{id}.xml"; /// <summary> /// Adjust the Root url user by the Route Builder. /// The default root value is `https://myanimelist.net` /// </summary> /// <param name="newRoot">New value to set</param> public static void AdjustRoot(string newRoot) { Parts.Root = newRoot; } /// <summary> /// Get url for retrieving an Anime`s cast /// /// <remarks> /// The placeholder is required because of the way Mal does routing. Thank to Raven for pointing out that the actual value does not matter /// </remarks> /// </summary> /// <param name="id">MAL Id</param> /// <returns>Anime cast URL</returns> public static string AnimeCastUrl(int id) => $"{Parts.Root}/{Parts.Anime}/{id}/{Parts.Placeholder}/{Parts.Characters}"; /// <summary> /// Get url for retrieving a character's page /// </summary> /// <param name="id">Character's Mal Id</param> /// <returns>Character url</returns> public static string AnimeCharacterUrl(int id) => $"{Parts.Root}/{Parts.Character}/{id}"; /// <summary> /// Get the url for retrieve an anime /// </summary> /// <param name="id">MAL Id</param> /// <returns>Anime Url</returns> public static string AnimeUrl(int id) => $"{Parts.Root}/{Parts.Anime}/{id}"; /// <summary> /// Append a route onto the MAL root /// </summary> /// <param name="route">Route to append</param> /// <returns>Full MAL url for the route</returns> public static string MalCleanUrl(string route) { return route.StartsWith("/") ? $"{Parts.Root}{route}" : $"{Parts.Root}/{route}"; } /// <summary> /// Url for retrieving season information /// </summary> /// <param name="year">Year for which data should be retrieved</param> /// <param name="season">Season for which data should be retrieved</param> /// <returns>Season lookup url</returns> public static string SeasonUrl(int year, Seasons season) => $"{Parts.Root}/{Parts.Anime}/{Parts.Season}/{year}/{season.ToString().ToLower(CultureInfo.InvariantCulture)}"; /// <summary> /// Url for retrieving Seiyuu /// </summary> /// <param name="id">Seiyuu Id</param> /// <returns>Seiyuu page url</returns> public static string SeiyuuUrl(int id) => $"{Parts.Root}/{Parts.People}/{id}"; /// <summary> /// Url for updating a user's anime /// </summary> /// <param name="id">Id of anime to update</param> /// <returns>Anime update url</returns> public static string UpdateAnime(int id) => $"{Parts.Root}/{Parts.Api}/{Parts.AnimeList}/{Parts.Update}/{id}.xml"; //TODO - Make more generic /// <summary> /// Url for retrieving a user's list /// </summary> /// <param name="username">Username for which list should be retrieved</param> /// <returns>User list url</returns> public static string UserListUrl(string username) => $"{Parts.Root}/{Parts.AppInfo}?u={username}&status=all&type=anime"; /// <summary> /// Url for verifying account credentials /// </summary> public static string VerifyCredentialsUrl() => $"{Parts.Root}/{Parts.Api}/{Parts.Account}/{Parts.VerifyCredentialsPage}"; #endregion /// <summary> /// Contains parts that can be used to construct Urls /// </summary> internal static class Parts { #region Properties /// <summary> /// MAL root url /// </summary> public static string Root { get; set; } = "https://myanimelist.net"; #endregion #region Variables /// <summary> /// Anime route part /// </summary> public const string Anime = "anime"; /// <summary> /// Characters route part /// </summary> public const string Characters = "characters"; /// <summary> /// Character route part /// </summary> public const string Character = "character"; /// <summary> /// API route part /// </summary> public const string Api = "api"; /// <summary> /// Account route part /// </summary> public const string Account = "account"; /// <summary> /// Verify credentials route part /// </summary> public const string VerifyCredentialsPage = "verify_credentials.xml"; /// <summary> /// App info route part /// </summary> public const string AppInfo = "malappinfo.php"; /// <summary> /// Season route part /// </summary> public const string Season = "season"; /// <summary> /// Anime list route part /// </summary> public const string AnimeList = "animelist"; /// <summary> /// Add route part /// </summary> public const string Add = "add"; /// <summary> /// Update route part /// </summary> public const string Update = "update"; /// <summary> /// People route part /// </summary> public const string People = "people"; /// <summary> /// Just a placeholder /// </summary> public const string Placeholder = "x"; #endregion } } }
using SPA.Models; using SPA.Models.DAO; using SPA.Models.Email; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SPA { public partial class ApplicationSPAConnexion : Form { public ApplicationSPAConnexion() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void buttonConnexion_Click(object sender, EventArgs e) { string valueLogin = textBoxIdentifiant.Text.Trim(); string valuePassword = textBoxPassword.Text.Trim(); if (!string.IsNullOrEmpty(valueLogin) && !string.IsNullOrEmpty(valuePassword)) { int res = verifConnexion(valueLogin, valuePassword); if (res != -1) { Personne utilisateur = Personne.GetPersonneById(res); labelConnexionError.Visible = false; Accueil accueil = new Accueil(this, utilisateur); accueil.Show(); this.Hide(); textBoxIdentifiant.Text = ""; textBoxPassword.Text = ""; } else { labelConnexionError.Visible = true; } } } private int verifConnexion(string login, string password) { return Session.ExistSession(login, password); } } }
using XH.Infrastructure.Query; namespace XH.Queries.Security.Queries { public class ListRolesQuery : ListQueryBase { public string Keywords { get; set; } public string Permission { get; set; } } }
using Senai.Peoples.WebAp.Domains; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Senai.Peoples.WebAp.Interfaces { interface IFuncionarioRepository { /// <summary> /// Me mostra todos os funcionarios do sistema /// </summary> /// <returns>lista de funcionarios</returns> List<FuncionarioDomain> ListarTodos(); /// <summary> /// Busca um funcionario pelo id /// </summary> /// <param name="id"> id do usuario buscado</param> /// <returns>um objeto funcionarioDomain que foi buscado</returns> FuncionarioDomain BuscarPorId(int id); /// <summary> /// Cadastra um novo funcionario /// </summary> /// <param name="novoFuncionario">Objeto funcionario com as informacoes do novo funcionario</param> void Cadastrar(FuncionarioDomain novoFuncionario); /// <summary> /// Atualiza as informacoes do funcionario /// </summary> /// <param name="id">id do funcionario que sera atualizado</param> /// <param name="funcionario"> Objeto funciorario com as novas informacoes</param> void AtualizarIdUrl(int id, FuncionarioDomain funcionario); /// <summary> /// Deleta um funcionario /// </summary> /// <param name="id">id do funcionaro que sera deletado</param> void deletar(int id); } }
// Copyright 2013-2015 Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Serilog.Events; /// <summary> /// Descriptive aliases for <see cref="LogEventLevel"/>. /// </summary> /// <remarks>These do not appear as members of the enumeration /// as duplicated underlying values result in issues when presenting /// enum values with <see cref="object.ToString()"/>.</remarks> public static class LevelAlias { /// <summary> /// The least significant level of event. /// </summary> public const LogEventLevel Minimum = LogEventLevel.Verbose; /// <summary> /// The most significant level of event. /// </summary> public const LogEventLevel Maximum = LogEventLevel.Fatal; /// <summary> /// A value that, when used as a "minimum" level, will result in no /// events being emitted. /// </summary> /// <remarks>It is never correct to construct a <see cref="LogEvent"/> with this value.</remarks> public const LogEventLevel Off = Maximum + 1; }
namespace PROG1_PROYECTO_FINAL { partial class Reporte_Factura { } } namespace PROG1_PROYECTO_FINAL.Reporte_FacturaTableAdapters { public partial class GenerarFacturaTableAdapter { } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.IO; using System.Reactive.Linq; using System.Threading; using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.XtraLayout.Utils; using VideoPlayer.Properties; using Vlc.DotNet.Core; using Vlc.DotNet.Forms; using Vlc.DotNet.Forms.TypeEditors; namespace VideoPlayer { public sealed partial class VideoPlayerXtraUserControl : XtraUserControl { private readonly VlcControl playerControl = new VlcControl(); private TimeSpan duration = TimeSpan.Zero; private IDisposable endReachedSubscription; private IDisposable playingSubscription; private IDisposable repeatSubscription; private IDisposable timeChangedSubscription; private Uri videoUrl; public VideoPlayerXtraUserControl() { InitializeComponent(); } [Category( "Video control settings" )] [Editor( typeof ( DirectoryEditor ), typeof ( UITypeEditor ) )] // ReSharper disable once MemberCanBePrivate.Global public DirectoryInfo VlcLibDirectory { // ReSharper disable once UnusedMember.Global set { playerControl.VlcLibDirectory = value; } get { return playerControl.VlcLibDirectory; } } public bool ShowNavigation { set; get; } private void InitPlayerControl() { playerControl.BeginInit(); panelControlVideo.Controls.Add( playerControl ); playerControl.Dock = DockStyle.Fill; timeChangedSubscription = Observable.FromEventPattern< EventHandler< VlcMediaPlayerTimeChangedEventArgs >, VlcMediaPlayerTimeChangedEventArgs >( h => playerControl.TimeChanged += h, h => playerControl.TimeChanged -= h ). ObserveOn( SynchronizationContext.Current ). Subscribe( e => PlayerControlOnTimeChanged( e.EventArgs ) ); endReachedSubscription = Observable.FromEventPattern< EventHandler< VlcMediaPlayerEndReachedEventArgs >, VlcMediaPlayerEndReachedEventArgs >( h => playerControl.EndReached += h, h => playerControl.EndReached -= h ). ObserveOn( SynchronizationContext.Current ). Subscribe( e => PlayerControlOnEndReached() ); playingSubscription = Observable.FromEventPattern< EventHandler< VlcMediaPlayerPlayingEventArgs >, VlcMediaPlayerPlayingEventArgs >( h => playerControl.Playing += h, h => playerControl.Playing -= h ). ObserveOn( SynchronizationContext.Current ). Subscribe( e => PlayerControlOnPlaying() ); playerControl.EndInit(); } private void PlayerControlOnEndReached() { progressBarControl1.Position = 0; layoutControlItemImage.Visibility = LayoutVisibility.Always; layoutControlItemVideo.Visibility = layoutControlItemButton.Visibility = layoutControlIteProgress.Visibility = LayoutVisibility.Never; pictureEdit1.Image = Resources.repeat_128; repeatSubscription = Observable.FromEventPattern< EventHandler, EventArgs >( h => pictureEdit1.Click += h, h => pictureEdit1.Click -= h ).Subscribe( e => StartPlaying() ); } private void PlayerControlOnTimeChanged( VlcMediaPlayerTimeChangedEventArgs e ) { progressBarControl1.Position = ( int ) e.NewTime; } private void PlayerControlOnPlaying() { progressBarControl1.Properties.Maximum = Convert.ToInt32( playerControl.GetCurrentMedia().Duration.TotalMilliseconds ); layoutControlItemImage.Visibility = LayoutVisibility.Never; layoutControlItemVideo.Visibility = LayoutVisibility.Always; if ( ShowNavigation ) layoutControlItemButton.Visibility = layoutControlIteProgress.Visibility = LayoutVisibility.Always; simpleButtonPlayStop.Image = Resources.pause_32; } protected override void Dispose( bool disposing ) { if ( disposing ) { if ( repeatSubscription != null ) repeatSubscription.Dispose(); if ( timeChangedSubscription != null ) timeChangedSubscription.Dispose(); if ( playingSubscription != null ) playingSubscription.Dispose(); if ( endReachedSubscription != null ) endReachedSubscription.Dispose(); if ( components != null ) components.Dispose(); if ( playerControl != null ) { try { playerControl.Stop(); playerControl.Dispose(); } catch ( AccessViolationException ) { } } } base.Dispose( disposing ); } public void Init( string url ) { InitPlayerControl(); videoUrl = new Uri( url ); StartPlaying(); } private void StartPlaying() { if ( repeatSubscription != null ) repeatSubscription.Dispose(); pictureEdit1.Image = Resources.WaitGear; playerControl.Play( videoUrl ); } private void progressBarControl1_MouseDown( object sender, MouseEventArgs e ) { playerControl.Time = GetTimeValue( e.Location ); } private void simpleButtonPlayStop_Click( object sender, EventArgs e ) { if ( playerControl.IsPlaying ) { playerControl.Pause(); simpleButtonPlayStop.Image = Resources.play_32; } else { playerControl.Play(); simpleButtonPlayStop.Image = Resources.pause_32; } } private void progressBarControl1_Properties_MouseMove( object sender, MouseEventArgs e ) { progressBarControl1.ToolTipController.ShowHint( TimeSpan.FromMilliseconds( GetTimeValue( e.Location ) ).ToString( @"hh\:mm\:ss\.f" ), progressBarControl1.PointToScreen( e.Location ) ); } private int GetTimeValue( Point e ) { return Convert.ToInt32( e.X * 1f / progressBarControl1.Width * progressBarControl1.Properties.Maximum ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SimpleImageHelper.HtmlHelpers { public static class HtmlHelperExtensions { public static MvcHtmlString Image(this HtmlHelper helper, string image, string alternative) { var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); var url = urlHelper.Action("Image", "Image", new { image }); var builder = new TagBuilder("img"); builder.MergeAttribute("src", url); builder.MergeAttribute("alt", alternative); return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); } } }
#include<stdio.h> #include<conion.h> void main() { printtf("Hello, World"); }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections; using System.Collections.Generic; using System; /// <summary> /// 2D : Visual Novel: Choice : Sequencer Command /// Shows several options each option jumps you to another section /// </summary> using System.Linq; [Serializable] public class SC_VN_Choice : SequencerCommandBase { public override string commandId{ get { return "choice"; } } public override string commandType{ get { return "base"; } } public int size = 0; public List<int> sectionIndexList; public List<string> optionTextList; public List<int> commandIndexList; override public void initChild() { } override public SequencerCommandBase clone() { SC_VN_Choice newCmd = ScriptableObject.CreateInstance(typeof(SC_VN_Choice)) as SC_VN_Choice; newCmd.size = size; newCmd.sectionIndexList = new List<int>(sectionIndexList.ToArray()); newCmd.optionTextList = new List<string>(optionTextList.ToArray()); newCmd.commandIndexList = new List<int>(commandIndexList.ToArray()); return base.clone(newCmd); } override public void execute(SequencePlayer player) { myPlayer = player; showChoices(); myPlayer.inRewindMode = false; } private void showChoices() { string[] nicks = sequencerData.getSectionNames(); List<ChoiceModel> choices = new List<ChoiceModel>(); for (int i = 0; i < sectionIndexList.Count; i++) { ChoiceModel model = new ChoiceModel(); model.text = optionTextList [i]; model.sceneNameToJump = nicks [sectionIndexList [i]]; model.sceneCommandIndexToJump = commandIndexList [i]; choices.Add(model); } myPlayer.choiceController.generateButtons(choices, myPlayer); } override public void undo() { myPlayer.choiceController.cleanup(); } override public void forward(SequencePlayer player) { //nothing, it blocks myPlayer.blockForward = true; } override public void backward(SequencePlayer player) { undo(); } #if UNITY_EDITOR override public void drawCustomUi() { EditorGUILayout.LabelField("number of options:"); size = EditorGUILayout.IntField(size); if (size > 0) { makeSureListsAreCorrectSize(); string[] nicks = sequencerData.getSectionNames(); EditorGUILayout.BeginVertical(); { for (int i = 0; i < size; i++) { EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Option Text:"); optionTextList [i] = EditorGUILayout.TextField(optionTextList [i]); GUILayout.Label("Jump to Section:"); sectionIndexList [i] = EditorGUILayout.Popup(sectionIndexList [i], nicks, GUILayout.Width(100)); int[] commands = Enumerable.Repeat(0, sequencerData.sections [sectionIndexList [i]].commandList.Count).ToArray(); string[] commandStr = new string[commands.Length]; for (int c = 0; c < commands.Length; c++) { commandStr [c] = c.ToString(); } GUILayout.Label("Jump to command Index:"); commandIndexList [i] = EditorGUILayout.Popup(commandIndexList [i], commandStr); } EditorGUILayout.EndHorizontal(); } } EditorGUILayout.EndVertical(); } } #endif void makeSureListsAreCorrectSize() { if (sectionIndexList == null) sectionIndexList = new List<int>(size); if (optionTextList == null) optionTextList = new List<string>(size); if (commandIndexList == null) commandIndexList = new List<int>(size); if (sectionIndexList.Count < size) sectionIndexList.AddRange(Enumerable.Repeat(0, size - sectionIndexList.Count).ToList()); if (commandIndexList.Count < size) commandIndexList.AddRange(Enumerable.Repeat(0, size - commandIndexList.Count).ToList()); if (optionTextList.Count < size) optionTextList.AddRange(Enumerable.Repeat("option", size - optionTextList.Count).ToList()); commandIndexList = commandIndexList.GetRange(0, size); sectionIndexList = sectionIndexList.GetRange(0, size); optionTextList = optionTextList.GetRange(0, size); } }
using System; using System.Collections.Generic; using System.Windows.Input; using FPGADeveloperTools.Common; using FPGADeveloperTools.Common.Model.ModuleFiles; using FPGADeveloperTools.Common.ViewModel; using FPGADeveloperTools.Common.ViewModel.ModuleFiles; using FPGADeveloperTools.Common.ViewModel.Ports; using FPGADeveloperTools.Common.ViewModel.TestCases; using FPGADeveloperTools.NewTCWindow.View; using FPGADeveloperTools.NewTCWindow.ViewModel; using FPGADeveloperTools.TestbenchGenerator.Model; using FPGADeveloperTools.TestbenchGenerator.View; namespace FPGADeveloperTools.TestbenchGenerator.ViewModel { public class GeneratorViewModel : ViewModelBase, IGeneratable { private ModuleFileViewModel moduleFile; private TestCaseViewModel selectedTC; private ICommand generateCommand; private ICommand addCommand; private ICommand removeCommand; private ICommand initCommand; private GeneratorView view; private string problemAddToolTip; private string problemRemoveToolTip; private string problemGenerateToolTip; public string ProblemAddToolTip { get { return this.problemAddToolTip; } set { this.problemAddToolTip = value; OnPropertyChanged("ProblemAddToolTip"); } } public string ProblemRemoveToolTip { get { return this.problemRemoveToolTip; } set { this.problemRemoveToolTip = value; OnPropertyChanged("ProblemRemoveToolTip"); } } public string ProblemGenerateToolTip { get { return this.problemGenerateToolTip; } set { this.problemGenerateToolTip = value; OnPropertyChanged("ProblemGenerateToolTip"); } } public ModuleFileViewModel ModuleFile { get { return this.moduleFile; } set { this.moduleFile = value; this.OnPropertyChanged("CanAdd"); this.OnPropertyChanged("CanAddN"); this.OnPropertyChanged("CanGenerate"); this.OnPropertyChanged("CanGenerateN"); } } public List<PortViewModel> Inputs { get { if (this.ModuleFile != null) return this.ModuleFile.Ins; else return null; } set { this.ModuleFile.Ins = value; this.OnPropertyChanged("Inputs"); } } public List<PortViewModel> Outputs { get { if (this.ModuleFile != null) return this.ModuleFile.Outputs; else return null; } set { this.ModuleFile.Outputs = value; this.OnPropertyChanged("Outputs"); } } public List<ParameterViewModel> Parameters { get { if (this.ModuleFile != null) return this.ModuleFile.Parameters; else return null; } set { this.ModuleFile.Parameters = value; this.OnPropertyChanged("Parameters"); } } public List<ClockViewModel> Clocks { get { if (this.ModuleFile != null) return this.ModuleFile.Clocks; else return null; } set { this.ModuleFile.Clocks = value; this.OnPropertyChanged("Clocks"); } } public List<ResetViewModel> Resets { get { if (this.ModuleFile != null) return this.ModuleFile.Resets; else return null; } set { this.ModuleFile.Resets = value; this.OnPropertyChanged("Resets"); } } public List<TestCaseViewModel> TestCases { get { if (this.ModuleFile != null) return this.ModuleFile.TestCases; else return null; } set { this.ModuleFile.TestCases = value; this.OnPropertyChanged("TestCases"); this.OnPropertyChanged("CanRemove"); this.OnPropertyChanged("CanRemoveN"); } } public TestCaseViewModel SelectedTestCase { get { return this.selectedTC; } set { this.selectedTC = value; this.OnPropertyChanged("SelectedTestCase"); this.OnPropertyChanged("CanRemove"); this.OnPropertyChanged("CanRemoveN"); } } public bool CanAdd { get { if(this.ModuleFile == null) { this.ProblemAddToolTip = "No module under test source file loaded."; return false; } this.ProblemAddToolTip = string.Empty; return true; } } public bool CanAddN { get { return !this.CanAdd; } } public bool CanRemove { get { string ptt = string.Empty; bool toRet = true; if(this.TestCases == null || this.TestCases.Count == 0) { ptt += "There are no testcases added.\n"; toRet = false; } if(this.SelectedTestCase == null) { ptt += "No testcase is selected.\n"; toRet = false; } if (ptt.EndsWith("\n")) ptt = ptt.Remove(ptt.Length - 1); this.ProblemRemoveToolTip = ptt; return toRet; } } public bool CanRemoveN { get { return !this.CanRemove; } } public bool CanGenerate { get { if (this.ModuleFile == null) { this.ProblemGenerateToolTip = "No module under test source file loaded."; return false; } this.ProblemGenerateToolTip = string.Empty; return true; } } public bool CanGenerateN { get { return !this.CanGenerate; } } public ICommand GenerateCommand { get { return this.generateCommand; } set { this.generateCommand = value; OnPropertyChanged("GenerateCommand"); } } public ICommand AddCommand { get { return this.addCommand; } set { this.addCommand = value; OnPropertyChanged("AddCommand"); } } public ICommand RemoveCommand { get { return this.removeCommand; } set { this.removeCommand = value; OnPropertyChanged("RemoveCommand"); } } public ICommand InitCommand { get { return this.initCommand; } set { this.initCommand = value; OnPropertyChanged("InitCommand"); } } public GeneratorViewModel(GeneratorView view) { this.view = view; this.GenerateCommand = new RelayCommand(new Action<object>(this.Generate)); this.AddCommand = new RelayCommand(new Action<object>(this.AddTC)); this.RemoveCommand = new RelayCommand(new Action<object>(this.RemoveTC)); this.InitCommand = new RelayCommand(new Action<object>(this.Init)); this.OnPropertyChanged("CanAdd"); this.OnPropertyChanged("CanAddN"); this.OnPropertyChanged("CanRemove"); this.OnPropertyChanged("CanRemoveN"); this.OnPropertyChanged("CanGenerate"); this.OnPropertyChanged("CanGenerateN"); } public void Generate(object obj) { bool result = this.GenerateFile(); this.view.infoBlock.Text = result ? DateTime.Now.ToLongTimeString() + " Testbench file generated successfully." : DateTime.Now.ToLongTimeString() + " Error - testbench file not generated."; } public bool GenerateFile() { string tbFilePath = String.Empty; if (this.ModuleFile is VerilogModuleFileViewModel) tbFilePath = this.ModuleFile.Path.Replace(".sv", "_tb.sv").Replace(".v", "_tb.sv"); else tbFilePath = this.ModuleFile.Path.Replace(".vhd", "_tb.sv"); FileGen file = new FileGen(this.ModuleFile.ModuleFile, tbFilePath); return file.GenerateFile(); } public void AddTC(object obj) { NewTCView newTCWindow = new NewTCView(new NewTCViewModel(this.ModuleFile)); newTCWindow.ShowDialog(); this.TestCases = ((NewTCViewModel)newTCWindow.DataContext).ModuleFileVM.TestCases; this.view.datains.Items.Refresh(); } public void RemoveTC(object obj) { this.TestCases.Remove(this.SelectedTestCase); this.SelectedTestCase = null; this.view.datains.Items.Refresh(); } public void Init(object obj) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".sv"; dlg.Filter = "SystemVerilog Files (*.sv)|*.sv|Verilog Files (*.v)|*.v|VHDL Files (*.vhd)|*.vhd"; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document string filename = dlg.FileName; this.LoadModule(filename); this.view.dutFile.Text = filename; } } public void LoadModule(string modulePath) { if (modulePath != null && modulePath != String.Empty) { if (modulePath.EndsWith(".sv") || modulePath.EndsWith(".v")) this.ModuleFile = new VerilogModuleFileViewModel(new VerilogModuleFile(modulePath)); else if (modulePath.EndsWith(".vhd")) this.ModuleFile = new VHDLModuleFileViewModel(new VHDLModuleFile(modulePath)); this.OnPropertyChanged("Clocks"); this.OnPropertyChanged("Resets"); this.OnPropertyChanged("Inputs"); this.OnPropertyChanged("Outputs"); this.OnPropertyChanged("Parameters"); } } } }
using SGCFT.Dados.Contextos; using SGCFT.Dominio.Contratos.Repositorios; using SGCFT.Dominio.Entidades; using System.Collections.Generic; using System.Linq; namespace SGCFT.Dados.Repositorios { public class RespostaRepositorio : IRespostaRepositorio { private readonly Contexto _contexto; public RespostaRepositorio() { _contexto = new Contexto(); } public void Inserir(Resposta resposta) { _contexto.Resposta.Add(resposta); _contexto.SaveChanges(); } public void Dispose() { if (_contexto != null) { _contexto.Dispose(); } } public List<Resposta> SelecionarRespostasPorIds(List<int> ids) { var respostas = _contexto.Resposta.Where(x => ids.Contains(x.Id)).ToList(); return respostas; } } }
using System; using System.Linq; using System.Threading.Tasks; using Serilog; using Witsml; using Witsml.Data; using Witsml.Extensions; using Witsml.ServiceReference; using WitsmlExplorer.Api.Jobs; using WitsmlExplorer.Api.Models; using WitsmlExplorer.Api.Query; using WitsmlExplorer.Api.Services; namespace WitsmlExplorer.Api.Workers { public class ModifyLogObjectWorker : IWorker<ModifyLogObjectJob> { private readonly IWitsmlClient witsmlClient; public ModifyLogObjectWorker(IWitsmlClientProvider witsmlClientProvider) { witsmlClient = witsmlClientProvider.GetClient(); } public async Task<(WorkerResult, RefreshAction)> Execute(ModifyLogObjectJob job) { Verify(job.LogObject); var wellUid = job.LogObject.WellUid; var wellboreUid = job.LogObject.WellboreUid; var logUid = job.LogObject.Uid; var query = CreateRequest(wellUid, wellboreUid, logUid, new WitsmlLog { Uid = logUid, UidWell = wellUid, UidWellbore = wellboreUid, Name = job.LogObject.Name }); var result = await witsmlClient.UpdateInStoreAsync(query); if (result.IsSuccessful) { Log.Information("{JobType} - Job successful", GetType().Name); var refreshAction = new RefreshWellbore(witsmlClient.GetServerHostname(), wellUid, wellboreUid, RefreshType.Update); return (new WorkerResult(witsmlClient.GetServerHostname(), true, $"Log updated ({job.LogObject.Name} [{logUid}])"), refreshAction); } Log.Error("Job failed. An error occurred when modifying log object: {Log}", job.LogObject.PrintProperties()); var logQuery = LogQueries.GetWitsmlLogById(wellUid, wellboreUid, logUid); var logs = await witsmlClient.GetFromStoreAsync(logQuery, new OptionsIn(ReturnElements.IdOnly)); var log = logs.Logs.FirstOrDefault(); EntityDescription description = null; if (log != null) { description = new EntityDescription { WellName = log.NameWell, WellboreName = log.NameWellbore, ObjectName = log.Name }; } return (new WorkerResult(witsmlClient.GetServerHostname(), false, "Failed to update log", result.Reason, description), null); } private static WitsmlLogs CreateRequest(string wellUid, string wellboreUid, string logUid, WitsmlLog logObject) { return new WitsmlLogs { Logs = new WitsmlLog { UidWell = wellUid, UidWellbore = wellboreUid, Uid = logUid, Name = logObject.Name }.AsSingletonList() }; } private void Verify(LogObject logObject) { if (string.IsNullOrEmpty(logObject.Name)) throw new InvalidOperationException($"{nameof(logObject.Name)} cannot be empty"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace trade.client { class FunctionList { public static Dictionary<string, Type> QuickBar = new Dictionary<string, Type>() { {"持仓查询", typeof(FrmQueryPositions) }, {"委托查询", typeof(FrmQueryOrders) }, {"成交查询", typeof(FrmQueryFills) }, {"交易", typeof(FrmTrade) }, {"ETF交易", typeof(FrmETF) }, {"交易回报", typeof(FrmReportSubscribe) }, }; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Obstacle : MonoBehaviour { void OnCollisionEnter(Collision collision) { //Check for a match with the specified name on any GameObject that collides with your GameObject if (collision.gameObject.name == "Fish") { collision.transform.forward = -collision.transform.forward; // collision.transform.rotation = Quaternion.LookRotation(transform.position - collision.gameObject.transform.position); //collision.transform.rotation = Quaternion.Slerp(transform.rotation, collision.gameObject.transform.rotation, Time.deltaTime * 15555); } } void Start() { } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace ArticleManage.ViewModels { public static class Utity { public static string DropHtml(string htmlstring, int strLen) { return CutString(DropHtml(htmlstring), strLen); } public static string CutString(string inputString, int len) { if (string.IsNullOrEmpty(inputString)) return ""; inputString = DropHtml(inputString); ASCIIEncoding ascii = new ASCIIEncoding(); int tempLen = 0; string tempString = ""; byte[] s = ascii.GetBytes(inputString); for (int i = 0; i < s.Length; i++) { if ((int)s[i] == 63) { tempLen += 2; } else { tempLen += 1; } try { tempString += inputString.Substring(i, 1); } catch { break; } if (tempLen > len) break; } //如果截过则加上半个省略号 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString); if (mybyte.Length > len) tempString += "…"; return tempString; } public static string DropHtml(string htmlstring) { if (string.IsNullOrEmpty(htmlstring)) return ""; //删除脚本 htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); //删除HTML htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase); htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); htmlstring = htmlstring.Replace("<", ""); htmlstring = htmlstring.Replace(">", ""); htmlstring = htmlstring.Replace("\r\n", ""); htmlstring = HttpContext.Current.Server.HtmlEncode(htmlstring).Trim(); return htmlstring; } } }
using UserService.DTO; using UserService.Model; namespace UserService.Mapper { public static class CityMapper { public static CityDTO ToCityDTO(this City city) { var memento = city.GetMemento(); return new CityDTO() { Id = memento.Id, Name = memento.Name, CountryId = memento.Country.Id }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using UserNotifications; namespace ParPorApp.iOS { public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate { public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler) { base.WillPresentNotification(center, notification, completionHandler); completionHandler(UNNotificationPresentationOptions.Alert); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using SGCFT.Dominio.Entidades; using SGCFT.Utilitario; using System.Linq; namespace SGCFT.Dominio.Teste { [TestClass] public class PerguntaTeste { [TestMethod] public void CriarNovaPerguntaComTextoValido() { string texto = "Qual seu nome?"; int idAutor = 3; int idModulo = 2; Pergunta pergunta = new Pergunta(texto,idAutor, idModulo); Retorno perguntaValida = pergunta.ValidarDominio(); Assert.AreEqual(true, perguntaValida.Sucesso); Assert.AreEqual(false, perguntaValida.Mensagens.Any()); } [TestMethod] public void CriarNovaPerguntaComTextoInvalido() { string texto = null; int autor = 3; int idModulo = 2; Pergunta pergunta = new Pergunta(texto,autor, idModulo); Retorno perguntaValida = pergunta.ValidarDominio(); Assert.AreEqual(false, perguntaValida.Sucesso); Assert.AreEqual("Pergunta inválida!", perguntaValida.Mensagens.First()); } [TestMethod] public void CriarNovaPerguntaComAutorInvalido() { string texto = null; int autor = ' '; int idModulo = 2; Pergunta pergunta = new Pergunta(texto, autor, idModulo); Retorno perguntaValida = pergunta.ValidarDominio(); Assert.AreEqual(false, perguntaValida.Sucesso); Assert.AreEqual("Pergunta inválida!", perguntaValida.Mensagens.First()); } } }
using Moq; using Moq.Language.Flow; using System.Threading; using System.Threading.Tasks; namespace DDMedi.UnitTest.Helper { public static class SetUpMockHelper { public static ISetup<IDDBroker, Task<TOutput>> SetUpProcessAsyncAny<TInputs, TOutput>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs<TOutput> => ddBroker.Setup(item => item.ProcessAsync<TInputs, TOutput>(It.IsAny<TInputs>(), It.IsAny<CancellationToken>())); public static ISetup<IDDBroker, Task> SetUpProcessAsyncAny<TInputs>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs => ddBroker.Setup(item => item.ProcessAsync(It.IsAny<TInputs>(), It.IsAny<CancellationToken>())); public static ISetup<IDDBroker, TOutput> SetUpProcessAny<TInputs, TOutput>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs<TOutput> => ddBroker.Setup(item => item.Process<TInputs, TOutput>(It.IsAny<TInputs>())); public static ISetup<IDDBroker> SetUpProcessAny<TInputs>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs => ddBroker.Setup(item => item.Process(It.IsAny<TInputs>())); public static void SetUpDDBrokerAndContext<TInputs>(out Mock<IDDBroker> ddBroker, out Mock<ISupplierContext<TInputs>> context) { context = new Mock<ISupplierContext<TInputs>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); } public static void SetUpDDBrokerAndContext<TInputs>(this TInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<ISupplierContext<TInputs>> context) { SetUpDDBrokerAndContext(out ddBroker, out context); context.Setup(e => e.Inputs).Returns(inputs); } public static void SetUpDDBrokerAndContext<TInputs, TOutput>(this TInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<IAsyncDecoratorContext<TInputs, TOutput>> context) where TInputs : IInputs<TOutput> { context = new Mock<IAsyncDecoratorContext<TInputs, TOutput>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); context.Setup(e => e.Inputs).Returns(inputs); } public static void SetUpDDBrokerAndContext<TInputs>(this TInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<IAsyncDecoratorContext<TInputs>> context) where TInputs : IInputs { context = new Mock<IAsyncDecoratorContext<TInputs>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); context.Setup(e => e.Inputs).Returns(inputs); } public static void SetUpDDBrokerAndContext<TInputs, TOutput>(this TInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<IDecoratorContext<TInputs, TOutput>> context) where TInputs : IInputs<TOutput> { context = new Mock<IDecoratorContext<TInputs, TOutput>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); context.Setup(e => e.Inputs).Returns(inputs); } public static void SetUpDDBrokerAndContext<TInputs>(this TInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<IDecoratorContext<TInputs>> context) where TInputs : IInputs { context = new Mock<IDecoratorContext<TInputs>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); context.Setup(e => e.Inputs).Returns(inputs); } public static void SetUpDDBrokerAndContext<TEInputs>(this TEInputs inputs, out Mock<IDDBroker> ddBroker, out Mock<IEDecoratorContext<TEInputs>> context) where TEInputs : IEInputs { context = new Mock<IEDecoratorContext<TEInputs>>(); ddBroker = new Mock<IDDBroker>(); context.Setup(e => e.DDBroker).Returns(ddBroker.Object); context.Setup(e => e.Inputs).Returns(inputs); } public static Mock<IAsyncSupplierChannel<TInputs, TOutput>> SetUpAsyncSupplierChannelAny<TInputs, TOutput>(this Mock<IDDBroker> ddBroker, TOutput output) where TInputs : IInputs<TOutput> { var mockSupplierChannel = new Mock<IAsyncSupplierChannel<TInputs, TOutput>>(); mockSupplierChannel.Setup(e => e.ProcessAsync(It.IsAny<TInputs>(), It.IsAny<CancellationToken>())).ReturnsAsync(output); ddBroker.Setup(item => item.CreateAsyncSupplierChannel<TInputs, TOutput>()).Returns(mockSupplierChannel.Object); return mockSupplierChannel; } public static Mock<IAsyncSupplierChannel<TInputs>> SetUpAsyncSupplierChannelAny<TInputs>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs { var mockSupplierChannel = new Mock<IAsyncSupplierChannel<TInputs>>(); mockSupplierChannel.Setup(e => e.ProcessAsync(It.IsAny<TInputs>(), It.IsAny<CancellationToken>())); ddBroker.Setup(item => item.CreateAsyncSupplierChannel<TInputs>()).Returns(mockSupplierChannel.Object); return mockSupplierChannel; } public static Mock<ISupplierChannel<TInputs, TOutput>> SetUpSupplierChannelAny<TInputs, TOutput>(this Mock<IDDBroker> ddBroker, TOutput output) where TInputs : IInputs<TOutput> { var mockSupplierChannel = new Mock<ISupplierChannel<TInputs, TOutput>>(); mockSupplierChannel.Setup(e => e.Process(It.IsAny<TInputs>())).Returns(output); ddBroker.Setup(item => item.CreateSupplierChannel<TInputs, TOutput>()).Returns(mockSupplierChannel.Object); return mockSupplierChannel; } public static Mock<ISupplierChannel<TInputs>> SetUpSupplierChannelAny<TInputs>(this Mock<IDDBroker> ddBroker) where TInputs : IInputs { var mockSupplierChannel = new Mock<ISupplierChannel<TInputs>>(); mockSupplierChannel.Setup(e => e.Process(It.IsAny<TInputs>())); ddBroker.Setup(item => item.CreateSupplierChannel<TInputs>()).Returns(mockSupplierChannel.Object); return mockSupplierChannel; } public static ISetup<IAsyncDecoratorContext<TInputs,TOutput>,Task<TOutput>> SetUpNextAny<TInputs, TOutput>(this IAsyncDecorator<TInputs, TOutput> decorator, Mock<IAsyncDecoratorContext<TInputs, TOutput>> context) where TInputs : IInputs<TOutput> => context.Setup(item => item.Next( It.IsAny<CancellationToken>())); public static ISetup<IAsyncDecoratorContext<TInputs>, Task> SetUpNextAny<TInputs>(this IAsyncDecorator<TInputs> decorator, Mock<IAsyncDecoratorContext<TInputs>> context) where TInputs : IInputs => context.Setup(item => item.Next(It.IsAny<CancellationToken>())); public static ISetup<IDecoratorContext<TInputs, TOutput>, TOutput> SetUpNextAny<TInputs, TOutput>(this IDecorator<TInputs, TOutput> decorator, Mock<IDecoratorContext<TInputs, TOutput>> context) where TInputs : IInputs<TOutput> => context.Setup(item => item.Next()); public static ISetup<IDecoratorContext<TInputs>> SetUpNextAny<TInputs>(this IDecorator<TInputs> decorator, Mock<IDecoratorContext<TInputs>> context) where TInputs : IInputs => context.Setup(item => item.Next()); public static ISetup<IEDecoratorContext<TEInputs>, Task> SetUpNextAny<TEInputs>(this IEDecorator<TEInputs> decorator, Mock<IEDecoratorContext<TEInputs>> context) where TEInputs : IEInputs => context.Setup(item => item.Next(It.IsAny<CancellationToken>())); } }
using System; using Autofac; using Framework.Core.Common; using Framework.Core.Helpers.PDF; using NUnit.Framework; using Tests.Data.Van; using Tests.Data.Van.Input.Filters; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main.Common.DefaultPage; using Tests.Pages.Van.Main.PdfPages; using Tests.Pages.Van.Main.ScriptSortOptions; using Tests.Pages.Van.Main.WalkManagerPages; namespace Tests.Projects.Van.WalkManagerTests.PrintTests { public class PrintCoverSheet : BaseTest { #region Test Pages private Driver Driver { get { return Scope.Resolve<Driver>(); } } private LoginPage LogInPage { get { return Scope.Resolve<LoginPage>(); } } private VoterDefaultPage HomePage { get { return Scope.Resolve<VoterDefaultPage>(); } } private WalkManagerListPage WalkManagerListPage { get { return Scope.Resolve<WalkManagerListPage>(); } } private WalkManagerDetailsPage WalkManagerDetailsPage { get { return Scope.Resolve<WalkManagerDetailsPage>(); } } private PdfPrintJobListPage PdfPrintJobListPage { get { return Scope.Resolve<PdfPrintJobListPage>(); } } #endregion #region Test Case Data #region TestCase: Print Single Cover Sheet - LibUK private static readonly VanTestUser User1 = new VanTestUser { UserName = "WalkManagerTester3", Password = "@uT0Te$t3InG", ClientId = "libuk", Site = "teamgreen.dev.local" }; private static readonly WalkManagerListPageFilter Filter1 = new WalkManagerListPageFilter { LocalAuthority = "Aberdeen City" }; private const string PollingDistrict1 = "CN0603"; private const string WalkToPrint1 = "Walk Turf Set Turf 01"; #endregion private static readonly object[] TestData = { new object[] { User1, Filter1, PollingDistrict1, WalkToPrint1 } }; #endregion [Ignore] // Error with generated PDF being corrupted. Working to figure this out. [Test, TestCaseSource("TestData")] public void PrintCoverSheetTest( VanTestUser user, WalkManagerListPageFilter filter, string pollingDistrictToOpen, string walkToPrint) { LogInPage.Login(user); HomePage.ClickWalkManagerLink(); WalkManagerListPage.OpenPollingDistrict(filter, pollingDistrictToOpen); WalkManagerDetailsPage.PrintCoverSheet(walkToPrint); // Extra space in title. HTML needs to be fixed. var title = String.Format("District Walk Turf {0} - {1} ", pollingDistrictToOpen, walkToPrint); PdfPrintJobListPage.ClickDownloadLink(title); // TODO: Nail down PDF validation //// Workaround for certificate issue. NOT GOOD PRACTICE //System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true; //// This PDF Validation is incorrect //Assert.That(PdfHelper.DoesPdfSectionExist(Driver.GetUrl(), "Title", 1), Is.True, // "PDF did not contain the proper section."); } } }
using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Sitecore.Framework.Runtime.Configuration; using Avanade.Plugin.IdentityProvider.Ids4Facebook.Configuration; using System; using Microsoft.AspNetCore.Authentication.Facebook; namespace Avanade.Plugin.IdentityProvider.Ids4Facebook { public class ConfigureSitecore { private readonly ILogger<ConfigureSitecore> _logger; private readonly AppSettings _appSettings; public ConfigureSitecore(ISitecoreConfiguration scConfig, ILogger<ConfigureSitecore> logger) { _logger = logger; _appSettings = new AppSettings(); scConfig.GetSection(AppSettings.SectionName).Bind(_appSettings.Ids4FacebookIdentityProvider); } public void ConfigureServices(IServiceCollection services) { var identityProvider = _appSettings.Ids4FacebookIdentityProvider; if (!identityProvider.Enabled) return; _logger.LogDebug("Configure '" + identityProvider.DisplayName + "'. AuthenticationScheme = " + identityProvider.AuthenticationScheme + ", MetadataAddress = " + identityProvider.AppId + ", Wtrealm = " + identityProvider.AppSecret, Array.Empty<object>()); new AuthenticationBuilder(services).AddFacebook(identityProvider.AuthenticationScheme, identityProvider.DisplayName, (Action<FacebookOptions>)(options => { options.SignInScheme = "idsrv.external"; options.AppId = identityProvider.AppId; options.AppSecret = identityProvider.AppSecret; })); } } }
// <copyright file="ImageUtil.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ using System.Threading.Tasks; using FiroozehGameService.Core.ApiWebRequest; using FiroozehGameService.Models; using FiroozehGameService.Models.Enums; using FiroozehGameService.Models.Internal; namespace FiroozehGameService.Utils { internal static class ImageUtil { internal static async Task<ImageUploadResult> UploadProfileImage(byte[] imageBuffer) { if (imageBuffer.Length > 1000 * 1024) throw new GameServiceException("ProfileImage is Too Large").LogException(typeof(ImageUtil), DebugLocation.Internal, "UploadProfileImage"); return await ApiRequest.UploadUserProfileLogo(imageBuffer); } internal static async Task<ImageUploadResult> UploadPartyLogo(byte[] imageBuffer, string partyId) { if (imageBuffer.Length > 1000 * 1024) throw new GameServiceException("Party Logo is Too Large").LogException(typeof(ImageUtil), DebugLocation.Internal, "UploadPartyLogo"); return await ApiRequest.UploadPartyLogo(imageBuffer, partyId); } } }
using UnityEngine; public class GameManager : MonoBehaviour { [SerializeField] private CardManager CardManager = null; [SerializeField] private SoundManager SoundManager = null; [SerializeField] private TextManager TextManager = null; [SerializeField] private TimeBarController TimeBarController = null; [SerializeField] private NarrationManager NarrationManager = null; [SerializeField] private LoadScene LoadScene = null; [SerializeField] private InfoPanel InfoPanel = null; [SerializeField] private BoardManager BoardManager = null; [SerializeField] private GameObject Cursor = null; [SerializeField] Transform[] transformsHnad = new Transform[2]; private bool turn = false; private int StartingLaneX = 0; private int handID = 0; private int faith = 0; private int cardID = 0, cardID0 = 0, cardID1 = 0; private int turnNum = 0; private bool isCPU = true; private int laneY = 0; public bool IsTimeLimit { get; set; } private void NextFaith() { faith++; if (faith > (int)EnumFaith.TurnChange) faith = (int)EnumFaith.Startup; } private void FaithUpdate() { switch (faith) { case (int)EnumFaith.Startup: Startup(); break; case (int)EnumFaith.Draw: Draw(); break; case (int)EnumFaith.SelectHand: SelectHand(); break; case (int)EnumFaith.Summon: SelectLane(); break; case (int)EnumFaith.Skill: Skill(); break; case (int)EnumFaith.Battle: Battle(); break; case (int)EnumFaith.TurnChange: TurnChange(); break; default: break; } } private void Startup() { Debug.Log(" ----------------------------------------------- "); TextManager.SetTurnNum(++turnNum); TextManager.SetPanel(turn); SoundManager.PlaySound((int)EnumAudioClips.NextTurn); NarrationManager.SetSerif((int)EnumNarrationTexts.NextPlayersTurn); SummonMonster(randomNum); NextFaith(); } private void SummonMonster(int randomNum) { if (turnNum % 5 == 0) { var laneY = randomNum < (int)EnumBoardLength.MaxBoardLengthY ? randomNum : (int)EnumBoardLength.MaxBoardY; if (laneY < (int)EnumBoardLength.MinBoard) return; var cardLanes = new CardLanes { X = (int)EnumBoardLength.MaxBoardX / 2, Y = laneY }; var canSummon = CardManager.CheckCanSummon(cardLanes); if (!canSummon) { SummonMonster(--laneY); } else if (canSummon) { CardManager.SummonMonster(Random.Range(0, (int)EnumNumbers.Monsters - 1), cardLanes); } turnNum = 0; } } private int randomNum; private void Draw() { randomNum = Random.Range(0, (int)EnumNumbers.Cards); cardID0 = randomNum; cardID1 = randomNum + 1 == 8 ? 0 : randomNum + 1; CardManager.Draw(cardID0, cardID1); TimeBarController.StartCoroutine(); NarrationManager.SetSerif((int)EnumNarrationTexts.SelectHand); NextFaith(); } private bool isInput = false; private void SelectHand() { if (Input.GetKeyDown(KeyCode.A)) { isInput = true; cardID = cardID0; handID = 0; Cursor.transform.position = transformsHnad[handID].transform.position; } else if (Input.GetKeyDown(KeyCode.D)) { isInput = true; cardID = cardID1; handID = 1; Cursor.transform.position = transformsHnad[handID].transform.position; } else if (Input.GetKeyDown(KeyCode.E) || IsTimeLimit) { if (!isInput) { cardID = cardID0; handID = 0; } isInput = false; IsTimeLimit = false; Cursor.transform.position = BoardManager.TransformList[StartingLaneX, laneY].transform.position; End(); } else if (isCPU && turn) { cardID = cardID0; handID = 0; End(); } void End() { if (handID == 0) { CardManager.DeleteHand(1); } else if (handID == 1) { CardManager.DeleteHand(0); } SoundManager.PlaySound((int)EnumAudioClips.Draw); NarrationManager.SetSerif((int)EnumNarrationTexts.SelectLane); TimeBarController.StopCoroutine(); TimeBarController.StartCoroutine(); NextFaith(); } } private void SelectLane() { if (Input.GetKeyDown(KeyCode.W)) { ++laneY; if (laneY == (int)EnumBoardLength.MaxBoardLengthY) laneY = (int)EnumBoardLength.MinBoard; Cursor.transform.position = BoardManager.TransformList[StartingLaneX, laneY].transform.position; } else if (Input.GetKeyDown(KeyCode.S)) { --laneY; if (laneY == (int)EnumBoardLength.MinBoard - 1) laneY = (int)EnumBoardLength.MaxBoardLengthY - 1; Cursor.transform.position = BoardManager.TransformList[StartingLaneX, laneY].transform.position; } else if (Input.GetKeyDown(KeyCode.E) || IsTimeLimit) { IsTimeLimit = false; End(); } else if (isCPU && turn) { laneY = Random.Range(0, (int)EnumBoardLength.MaxBoardLengthY); End(); } void End() { var canSummon = CardManager.CheckCanSummon(new CardLanes { X = StartingLaneX, Y = laneY }); if (!canSummon) { faith = (int)EnumFaith.Summon; } else if (canSummon) { Summon(laneY); TimeBarController.StopCoroutine(); TimeBarController.StartCoroutine(); NextFaith(); } } } private void Summon(int laneY) { if (!turn) { CardManager.Summon(new CardLanes { X = (int)EnumBoardLength.MinBoard, Y = laneY }, handID, cardID, turn); } else if (turn) { CardManager.Summon(new CardLanes { X = (int)EnumBoardLength.MaxBoardX, Y = laneY }, handID, cardID, turn); } SoundManager.PlaySound((int)EnumAudioClips.SpecialSummon); NarrationManager.SetSerif((int)EnumNarrationTexts.Battle); } private void Skill() { if (Input.GetKeyDown(KeyCode.E) || IsTimeLimit) { IsTimeLimit = false; TimeBarController.StopCoroutine(); NextFaith(); } } private void Battle() { if (!turn) { CardManager.Movement(1, turn); NextFaith(); } else if (turn) { CardManager.Movement(-1, turn); NextFaith(); } } private void TurnChange() { turn = !turn; if (turn) { StartingLaneX = (int)EnumBoardLength.MaxBoardX; } else if (!turn) { StartingLaneX = (int)EnumBoardLength.MinBoard; } handID = 0; laneY = 0; Cursor.transform.position = transformsHnad[handID].transform.position; NextFaith(); } private void Start() { LoadScene = new LoadScene(); Application.targetFrameRate = 30; } private void Update() { FaithUpdate(); if (Input.GetKeyDown(KeyCode.Tab)) { InfoPanel.PanelChange(); } else if (Input.GetKeyDown(KeyCode.T)) { isCPU = !isCPU; } else if (Input.GetKeyDown(KeyCode.P)) { LoadScene.ResetGames(); } else if (Input.GetKeyDown(KeyCode.Escape)) { LoadScene.ExitGames(); } } }
using SMG.Common.Algebra; using SMG.Common.Code; using SMG.Common.Gates; using SMG.Common.Transitions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace SMG.Common.Conditions { /// <summary> /// Base class for conditions based on variables values. /// </summary> public abstract class VariableCondition : Condition, IInput, IVariableCondition { #region Private private string _gateid; private IVariableCondition _transparent; #endregion #region Properties public IVariableCondition Parent { get; private set; } public Variable Variable { get; private set; } /// <summary> /// The index of the selected state. /// </summary> public int StateIndex { get; protected set; } public GateType Type { get { return GateType.Input; } } public string ID { get { return _gateid; } } public int Group { get { return Variable.Address; } } public virtual int Address { get { return Variable.Address; } } public int Cardinality { get { return Variable.Type.Cardinality; } } public virtual bool IsInverted { get { return false; } } public virtual bool IsTransition { get { return false; } } public virtual string CacheKey { get { var key = Variable.Name; // add parent key if this refers to a state transition condition. /*if(null != _transparent) { key += "$" + _transparent.Key; }*/ return key; } } #endregion #region Construction public VariableCondition(Variable v) { Variable = v; } public VariableCondition(IVariableCondition parent) { Debug.Assert(parent != this); Parent = parent; Variable = Parent.Variable; var top = Parent; while(null != top) { if(top.IsTransition) { _transparent = top; break; } top = top.Parent; } } #endregion #region Diagnostics public override string ToString() { string result; if (TraceFlags.ShowVariableAddress) { result = Variable.Name + "<" + Group + "," + Address + ">"; } else { result = Variable.Name; } return result; } #endregion #region IInput public void Freeze(string gateid) { if (null != _gateid) { throw new Exception("gate identifier already assigned."); } _gateid = gateid; } public virtual Factor CreateFactor() { throw new NotImplementedException(); } public virtual IGate Invert() { return new InvertedInput(this); } public bool IsFixed { get { return false; } } public Product GetProduct() { return new Product(CreateFactor()); } public IGate Simplify() { throw new NotImplementedException(); } IGate IGate.Clone() { throw new NotImplementedException(); } public abstract void Emit(ICodeGateEvaluator writer); public abstract IGate CreateElementaryCondition(int stateindex); #endregion #region ICondition public override IGate Decompose(ConditionMode mode) { return this; } #endregion #region IVariableCondition public override IEnumerable<Transition> GetTransitions() { if (null != Parent) { /*foreach (var t in Parent.GetTransitions()) { if (t.PreStateIndexes.Contains(StateIndex)) { t.PreStateIndexes = new[] { StateIndex }; yield return t; } }*/ throw new NotImplementedException(); } yield break; } #endregion } }
#region MIT License /* * Copyright (c) 2009 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen. */ using Physics2DDotNet; using System.Collections.Generic; using System; using Jypeli.Physics; namespace Jypeli { internal class AdaptedIgnorer : Physics2DDotNet.Ignorers.Ignorer { public Jypeli.Ignorer Adaptee { get; private set; } public override bool BothNeeded { get { return Adaptee.BothNeeded; } } public AdaptedIgnorer( Jypeli.Ignorer adaptee ) { this.Adaptee = adaptee; } protected override bool CanCollide( Body thisBody, Body otherBody, Physics2DDotNet.Ignorers.Ignorer otherIgnorer ) { var other = (PhysicsBody)( otherBody.Tag ); return Adaptee.CanCollide( (IPhysicsBody)thisBody.Tag, other, other.CollisionIgnorer ); } } public partial class PhysicsBody { private int _ignoreGroup = 0; private AdaptedIgnorer _adaptedIgnorer = null; /// <summary> /// Olio, jolla voi välttää oliota osumasta tiettyihin muihin olioihin. /// </summary> public virtual Ignorer CollisionIgnorer { get { return _adaptedIgnorer == null ? null : _adaptedIgnorer.Adaptee; } set { Body.CollisionIgnorer = _adaptedIgnorer = new AdaptedIgnorer( value ); } } /// <summary> /// Jättääkö olio törmäyksen huomioimatta. Jos tosi, törmäyksestä /// tulee tapahtuma, mutta itse törmäystä ei tapahdu. /// </summary> public bool IgnoresCollisionResponse { get { return Body.IgnoresCollisionResponse; } set { Body.IgnoresCollisionResponse = value; } } /// <summary> /// Tapahtuu kun olio törmää toiseen. /// </summary> public event CollisionHandler<IPhysicsBody, IPhysicsBody> Collided; private void OnCollided( object sender, CollisionEventArgs e ) { if ( Collided != null ) { var other = e.Other.Tag as IPhysicsBody; Collided( this, other ); } } /// <summary> /// Tapahtuu kun olio on törmäyksessä toiseen. /// </summary> public event AdvancedCollisionHandler<IPhysicsBody, IPhysicsBody> Colliding; private void OnColliding( object sender, CollisionEventArgs e ) { if ( Colliding != null ) { var other = e.Other.Tag as IPhysicsBody; var contacts = new List<Collision.ContactPoint>(); contacts.AddRange( e.Contact.Points.ConvertAll( p => new Collision.ContactPoint(p.Position, p.Normal) ) ); Colliding( this, other, new Collision(this, other, contacts) ); } } private static CollisionShapeParameters GetDefaultParameters( double width, double height ) { CollisionShapeParameters p; p.MaxVertexDistance = Math.Min( width, height ) / 3; p.DistanceGridSpacing = Math.Min( width, height ) / 2; return p; } /// <summary> /// Tekee oliosta läpimentävän alhaalta ylöspäin (tasohyppelytaso). /// Huom. ei toimi yhdessä CollisionIgnoreGroupien kanssa! /// </summary> public void MakeOneWay() { throw new NotImplementedException(); //this.CollisionIgnorer = new OneWayPlatformIgnorer( AdvanceMath.Vector2D.YAxis, Size.Y ); } /// <summary> /// Tekee oliosta läpimentävän vektorin suuntaan. /// Huom. ei toimi yhdessä CollisionIgnoreGroupien kanssa! /// </summary> public void MakeOneWay( Vector direction ) { throw new NotImplementedException(); //this.CollisionIgnorer = new OneWayPlatformIgnorer( (Vector2D)direction, Size.Y ); } } }
using System; namespace CourseHunter_91_Delegate { public class Car { // Делегаты представляют такие объекты, которые указывают на методы. // То есть делегаты - это указатели на методы // и с помощью делегатов мы можем вызвать данные методы. int speed = 0; // 1. Объявляем делегат. Который описывает сигнатуру того метода который будет вызываться. Синтаксис делегата. public delegate void TooFast(); // 2. Объявить переменную типа делегата. Экземпляр делегата. private TooFast tooFast; public void Start() { speed = 10; } public void Accelerate() { speed += 10; if (speed > 90) { tooFast(); // 5. Вызываем его. } } public void Stop() { speed = 0; } // 3. Метод обаботчик. Либо в конструкторе подисываемся на него либо отдельный метод. Метод, для того что бы подписаться на событие. public void RegisterOnTooFast (TooFast tooFast) { // 4. Запоминаем его в филду. this.tooFast = tooFast; } } class Program { static Car car; static void Main(string[] args) { car = new Car(); car.RegisterOnTooFast(HandleOnTooFast); car.Start(); for (int i = 0; i < 10; i++) { car.Accelerate(); } // Нам нужно уведомление с нижнего уровня,что хватит прибавлять скорость. Console.ReadLine(); } // 6. Клиенская часть. Создаем обработчик. private static void HandleOnTooFast() { Console.WriteLine("Oh, I got it, calling stop!"); car.Stop(); } } }
using FluentValidation; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; namespace SFA.DAS.ProviderCommitments.Web.Validators.Cohort { public class DeleteCohortViewModelValidator : AbstractValidator<DeleteCohortViewModel> { public DeleteCohortViewModelValidator() { RuleFor(x => x.ProviderId).GreaterThan(0); RuleFor(x => x.CohortReference).NotNull(); RuleFor(x => x.Confirm).NotNull().WithMessage("Confirm if you would like to delete this cohort"); } } }
using NUnit.Framework; using Moq; #pragma warning disable 618 namespace Emkay.S3.Tests { [TestFixture] public class EnumerateBucketsTests : S3TestsBase { [Test] public void should_find_all_buckets() { Mock.Get(MockS3Client).Setup(x => x.EnumerateBuckets()).Returns(new[] {"bucket1", "bucket2", "bucket3"}); var enumerateTask = new EnumerateBuckets(MockS3ClientFactory, MockLogger) { Key = FakeAwsKey, Secret = FakeAwsSecret, }; Assert.That(enumerateTask.Execute(), Is.True); Assert.That(enumerateTask.Buckets, Is.EquivalentTo(new[] { "bucket1", "bucket2", "bucket3" })); } } }
using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using Jobs.Controllers; using Data.Models; using Data.Infrastructure; using Service; using Model.Models; using AutoMapper; using Model.ViewModel; using Model.ViewModels; namespace Jobs.App_Start { /// <summary> /// Specifies the Unity configuration for the main container. /// </summary> public class UnityConfig { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Gets the configured Unity container. /// </summary> public static IUnityContainer GetConfiguredContainer() { return container.Value; } #endregion /// <summary>Registers the type mappings with the Unity container.</summary> /// <param name="container">The unity container to configure.</param> /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks> public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your types here // container.RegisterType<IProductRepository, ProductRepository>(); container.RegisterType<IRepository<SaleOrderHeader>, Repository<SaleOrderHeader>>(); container.RegisterType<Service.ISaleOrderHeaderService, Service.SaleOrderHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<SaleOrderLine>, Repository<SaleOrderLine>>(); container.RegisterType<Service.ISaleOrderLineService, Service.SaleOrderLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<SaleInvoiceHeaderCharge>, Repository<SaleInvoiceHeaderCharge>>(); container.RegisterType<ISaleInvoiceHeaderChargeService, SaleInvoiceHeaderChargeService>(new PerRequestLifetimeManager()); container.RegisterType<AccountController>(new InjectionConstructor()); //container.RegisterType<ApplicationDbContext, ApplicationDbContext>("New"); container.RegisterType<IDataContext, ApplicationDbContext>(new PerRequestLifetimeManager()); container.RegisterType<IUnitOfWorkForService, UnitOfWork>(new PerRequestLifetimeManager()); container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<BusinessEntity>, Repository<BusinessEntity>>(); container.RegisterType<IBusinessEntityService, BusinessEntityService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<LedgerAccount>, Repository<LedgerAccount>>(); container.RegisterType<IAccountService, AccountService>(new PerRequestLifetimeManager()); container.RegisterType<IExceptionHandlingService, ExceptionHandlingService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderHeader>, Repository<JobOrderHeader>>(); container.RegisterType<IJobOrderHeaderService, JobOrderHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderLine>, Repository<JobOrderLine>>(); container.RegisterType<IJobOrderLineService, JobOrderLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderSettings>, Repository<JobOrderSettings>>(); container.RegisterType<IJobOrderSettingsService, JobOrderSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobInvoiceSettings>, Repository<JobInvoiceSettings>>(); container.RegisterType<IJobInvoiceSettingsService, JobInvoiceSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobConsumptionSettings>, Repository<JobConsumptionSettings>>(); container.RegisterType<IJobConsumptionSettingsService, JobConsumptionSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveSettings>, Repository<JobReceiveSettings>>(); container.RegisterType<IJobReceiveSettingsService, JobReceiveSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveHeader>, Repository<JobReceiveHeader>>(); container.RegisterType<IJobReceiveHeaderService, JobReceiveHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveLine>, Repository<JobReceiveLine>>(); container.RegisterType<IJobReceiveLineService, JobReceiveLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveQAAttribute>, Repository<JobReceiveQAAttribute>>(); container.RegisterType<IJobReceiveQAAttributeService, JobReceiveQAAttributeService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveQAPenalty>, Repository<JobReceiveQAPenalty>>(); container.RegisterType<IJobReceiveQAPenaltyService, JobReceiveQAPenaltyService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReturnHeader>, Repository<JobReturnHeader>>(); container.RegisterType<IJobReturnHeaderService, JobReturnHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReturnLine>, Repository<JobReturnLine>>(); container.RegisterType<IJobReturnLineService, JobReturnLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveBom>, Repository<JobReceiveBom>>(); container.RegisterType<IJobReceiveBomService, JobReceiveBomService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobReceiveByProduct>, Repository<JobReceiveByProduct>>(); container.RegisterType<IJobReceiveByProductService, JobReceiveByProductService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderBom>, Repository<JobOrderBom>>(); container.RegisterType<IJobOrderBomService, JobOrderBomService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobInvoiceHeader>, Repository<JobInvoiceHeader>>(); container.RegisterType<IJobInvoiceHeaderService, JobInvoiceHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobInvoiceLine>, Repository<JobInvoiceLine>>(); container.RegisterType<IJobInvoiceLineService, JobInvoiceLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderCancelHeader>, Repository<JobOrderCancelHeader>>(); container.RegisterType<IJobOrderCancelHeaderService, JobOrderCancelHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderCancelLine>, Repository<JobOrderCancelLine>>(); container.RegisterType<IJobOrderCancelLineService, JobOrderCancelLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderAmendmentHeader>, Repository<JobOrderAmendmentHeader>>(); container.RegisterType<IJobOrderAmendmentHeaderService, JobOrderAmendmentHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobOrderRateAmendmentLine>, Repository<JobOrderRateAmendmentLine>>(); container.RegisterType<IJobOrderRateAmendmentLineService, JobOrderRateAmendmentLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobInvoiceAmendmentHeader>, Repository<JobInvoiceAmendmentHeader>>(); container.RegisterType<IJobInvoiceAmendmentHeaderService, JobInvoiceAmendmentHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobInvoiceRateAmendmentLine>, Repository<JobInvoiceRateAmendmentLine>>(); container.RegisterType<IJobInvoiceRateAmendmentLineService, JobInvoiceRateAmendmentLineService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<JobWorker>, Repository<JobWorker>>(); container.RegisterType<IJobWorkerService, JobWorkerService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<PersonAddress>, Repository<PersonAddress>>(); container.RegisterType<IPersonAddressService, PersonAddressService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<PersonProcess>, Repository<PersonProcess>>(); container.RegisterType<IPersonProcessService, PersonProcessService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<PersonRegistration>, Repository<PersonRegistration>>(); container.RegisterType<IPersonRegistrationService, PersonRegistrationService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<Person>, Repository<Person>>(); container.RegisterType<IPersonService, PersonService>(new PerRequestLifetimeManager()); // container.RegisterType<IRepository<ProductUid>, Repository<ProductUid>>(); container.RegisterType<IProductUidService, ProductUidService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<RateConversionSettings>, Repository<RateConversionSettings>>(); container.RegisterType<IRateConversionSettingsService, RateConversionSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<StockHeader>, Repository<StockHeader>>(); container.RegisterType<IStockHeaderService, StockHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IRepository<StockLine>, Repository<StockLine>>(); container.RegisterType<IStockLineService, StockLineService>(new PerRequestLifetimeManager()); container.RegisterType<IReportLineService, ReportLineService>(new PerRequestLifetimeManager()); container.RegisterType<IActivityLogService, ActivityLogService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderHeaderChargeService, JobOrderHeaderChargeService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderLineChargeService, JobOrderLineChargeService>(new PerRequestLifetimeManager()); container.RegisterType<IChargesCalculationService, ChargesCalculationService>(new PerRequestLifetimeManager()); container.RegisterType<IJobInvoiceHeaderChargeService, JobInvoiceHeaderChargeService>(new PerRequestLifetimeManager()); container.RegisterType<IJobInvoiceLineChargeService, JobInvoiceLineChargeService>(new PerRequestLifetimeManager()); container.RegisterType<IDuplicateDocumentCheckService, DuplicateDocumentCheckService>(new PerRequestLifetimeManager()); container.RegisterType<IPersonContactService, PersonContactService>(new PerRequestLifetimeManager()); container.RegisterType<IPersonBankAccountService, PersonBankAccountService>(new PerRequestLifetimeManager()); container.RegisterType<IRateListService, RateListService>(new PerRequestLifetimeManager()); container.RegisterType<IExcessJobReviewService, ExcessJobReviewService>(new PerRequestLifetimeManager()); container.RegisterType<IUpdateJobExpiryService, UpdateJobExpiryService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionRequestHeaderService, JobOrderInspectionRequestHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionRequestLineService, JobOrderInspectionRequestLineService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionRequestSettingsService, JobOrderInspectionRequestSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionSettingsService, JobOrderInspectionSettingsService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionRequestCancelHeaderService, JobOrderInspectionRequestCancelHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionRequestCancelLineService, JobOrderInspectionRequestCancelLineService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionHeaderService, JobOrderInspectionHeaderService>(new PerRequestLifetimeManager()); container.RegisterType<IJobOrderInspectionLineService, JobOrderInspectionLineService>(new PerRequestLifetimeManager()); //Registering Mappers: Mapper.CreateMap<BusinessEntity, AgentViewModel>(); Mapper.CreateMap<AgentViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, EmployeeViewModel>(); Mapper.CreateMap<EmployeeViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, SupplierViewModel>(); Mapper.CreateMap<SupplierViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, JobWorkerViewModel>(); Mapper.CreateMap<JobWorkerViewModel, BusinessEntity>(); Mapper.CreateMap<Person, JobWorkerViewModel>(); Mapper.CreateMap<JobWorkerViewModel, Person >(); Mapper.CreateMap<JobWorker, JobWorkerViewModel>(); Mapper.CreateMap<JobWorkerViewModel, JobWorker>(); Mapper.CreateMap<PersonAddress, JobWorkerViewModel>(); Mapper.CreateMap<JobWorkerViewModel, PersonAddress>(); Mapper.CreateMap<LedgerAccount, JobWorkerViewModel>(); Mapper.CreateMap<JobWorkerViewModel, LedgerAccount>(); Mapper.CreateMap<BusinessEntity, ManufacturerViewModel>(); Mapper.CreateMap<ManufacturerViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, CourierViewModel>(); Mapper.CreateMap<CourierViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, TransporterViewModel>(); Mapper.CreateMap<TransporterViewModel, BusinessEntity>(); Mapper.CreateMap<BusinessEntity, BuyerViewModel>(); Mapper.CreateMap<BuyerViewModel, BusinessEntity>(); Mapper.CreateMap<JobOrderHeader, JobOrderHeaderViewModel>(); Mapper.CreateMap<JobOrderHeaderViewModel, JobOrderHeader>(); Mapper.CreateMap<JobOrderLine, JobOrderLineViewModel>(); Mapper.CreateMap<JobOrderLineViewModel, JobOrderLine>(); Mapper.CreateMap<JobOrderSettings, JobOrderSettingsViewModel>(); Mapper.CreateMap<JobOrderSettingsViewModel, JobOrderSettings>(); Mapper.CreateMap<JobConsumptionSettings, JobConsumptionSettingsViewModel>(); Mapper.CreateMap<JobConsumptionSettingsViewModel, JobConsumptionSettings>(); Mapper.CreateMap<JobReceiveSettings, JobReceiveSettingsViewModel>(); Mapper.CreateMap<JobReceiveSettingsViewModel, JobReceiveSettings>(); Mapper.CreateMap<JobOrderPerk, PerkViewModel>(); Mapper.CreateMap<PerkViewModel, JobOrderPerk>().ForMember(m => m.CreatedDate, x => x.Ignore()).ForMember(m => m.CreatedBy, x => x.Ignore()) .ForMember(m => m.ModifiedDate, x => x.Ignore()) .ForMember(m => m.ModifiedBy, x => x.Ignore()); Mapper.CreateMap<Perk, PerkViewModel>(); Mapper.CreateMap<PerkViewModel, Perk>(); Mapper.CreateMap<LineChargeViewModel, CalculationProduct>().ForMember(m => m.CalculationProductId , x => x.Ignore()); Mapper.CreateMap<CalculationProduct, LineChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<LineChargeViewModel, JobOrderLineCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobOrderLineCharge, LineChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<HeaderChargeViewModel, JobOrderHeaderCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobOrderHeaderCharge, HeaderChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<LineChargeViewModel, JobInvoiceLineCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceLineCharge, LineChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<HeaderChargeViewModel, JobInvoiceHeaderCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceHeaderCharge, HeaderChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<LineChargeViewModel, JobInvoiceReturnLineCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceReturnLineCharge, LineChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<HeaderChargeViewModel, JobInvoiceReturnHeaderCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceReturnHeaderCharge, HeaderChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<HeaderChargeViewModel, JobInvoiceAmendmentHeaderCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceAmendmentHeaderCharge, HeaderChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<LineChargeViewModel, JobInvoiceRateAmendmentLineCharge>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobInvoiceRateAmendmentLineCharge, LineChargeViewModel>().ForMember(m => m.Id, x => x.Ignore()); Mapper.CreateMap<JobReceiveHeader, JobReceiveHeaderViewModel>(); Mapper.CreateMap<JobReceiveHeaderViewModel, JobReceiveHeader>(); Mapper.CreateMap<JobReceiveLine, JobReceiveLineViewModel>(); Mapper.CreateMap<JobReceiveLineViewModel, JobReceiveLine>(); Mapper.CreateMap<JobReturnHeader, JobReturnHeaderViewModel>(); Mapper.CreateMap<JobReturnHeaderViewModel, JobReturnHeader>(); Mapper.CreateMap<JobReturnLine, JobReturnLineViewModel>(); Mapper.CreateMap<JobReturnLineViewModel, JobReturnLine>(); Mapper.CreateMap<JobInvoiceHeader, JobInvoiceHeaderViewModel>(); Mapper.CreateMap<JobInvoiceHeaderViewModel, JobInvoiceHeader>(); Mapper.CreateMap<JobInvoiceLine, JobInvoiceLineViewModel>(); Mapper.CreateMap<JobInvoiceLineViewModel, JobInvoiceLine>(); Mapper.CreateMap<JobOrderCancelHeader, JobOrderCancelHeaderViewModel>(); Mapper.CreateMap<JobOrderCancelHeaderViewModel, JobOrderCancelHeader>(); Mapper.CreateMap<JobOrderCancelLine, JobOrderCancelLineViewModel>(); Mapper.CreateMap<JobOrderCancelLineViewModel, JobOrderCancelLine>(); Mapper.CreateMap<JobOrderAmendmentHeader, JobOrderAmendmentHeaderViewModel>(); Mapper.CreateMap<JobOrderAmendmentHeaderViewModel, JobOrderAmendmentHeader>(); Mapper.CreateMap<JobOrderRateAmendmentLine, JobOrderRateAmendmentLineViewModel>(); Mapper.CreateMap<JobOrderRateAmendmentLineViewModel, JobOrderRateAmendmentLine>(); Mapper.CreateMap<JobInvoiceAmendmentHeader, JobInvoiceAmendmentHeaderViewModel>(); Mapper.CreateMap<JobInvoiceAmendmentHeaderViewModel, JobInvoiceAmendmentHeader>(); Mapper.CreateMap<JobInvoiceRateAmendmentLine, JobInvoiceRateAmendmentLineViewModel>(); Mapper.CreateMap<JobInvoiceRateAmendmentLineViewModel, JobInvoiceRateAmendmentLine>(); Mapper.CreateMap<JobReceiveByProduct, JobReceiveByProductViewModel>(); Mapper.CreateMap<JobReceiveByProductViewModel, JobReceiveByProduct>(); Mapper.CreateMap<JobReceiveBom, JobReceiveBomViewModel>(); Mapper.CreateMap<JobReceiveBomViewModel, JobReceiveBom>(); Mapper.CreateMap<JobInvoiceSettings, JobInvoiceSettingsViewModel>(); Mapper.CreateMap<JobInvoiceSettingsViewModel, JobInvoiceSettings>(); Mapper.CreateMap<CalculationFooterViewModel, HeaderChargeViewModel>(); Mapper.CreateMap<CalculationProductViewModel, LineChargeViewModel>(); Mapper.CreateMap<RateConversionSettings, RateConversionSettingsViewModel>(); Mapper.CreateMap<RateConversionSettingsViewModel, RateConversionSettings>(); Mapper.CreateMap<StockHeader, StockHeaderViewModel>(); Mapper.CreateMap<StockHeaderViewModel, StockHeader>(); Mapper.CreateMap<StockLineViewModel, StockLine>(); Mapper.CreateMap<StockLine, StockLineViewModel>(); Mapper.CreateMap<PersonContact, PersonContactViewModel>(); Mapper.CreateMap<PersonContactViewModel, PersonContact>(); Mapper.CreateMap<JobInvoiceHeaderViewModel, JobReceiveHeader>(); Mapper.CreateMap<JobReceiveHeader, JobInvoiceHeaderViewModel>(); Mapper.CreateMap<JobInvoiceLineViewModel, JobReceiveLine>(); Mapper.CreateMap<JobReceiveLine, JobInvoiceLineViewModel>(); Mapper.CreateMap<RateListViewModel, RateList>(); Mapper.CreateMap<RateList, RateListViewModel>(); Mapper.CreateMap<RateList, RateListHistory>(); Mapper.CreateMap<RateListHistory, RateList>(); Mapper.CreateMap<HeaderChargeViewModel, HeaderChargeViewModel>(); Mapper.CreateMap<LineChargeViewModel, LineChargeViewModel>(); Mapper.CreateMap<JobInvoiceReturnHeader, JobInvoiceReturnHeaderViewModel>(); Mapper.CreateMap<JobInvoiceReturnHeaderViewModel, JobInvoiceReturnHeader>(); Mapper.CreateMap<JobInvoiceReturnHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobInvoiceReturnHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderSettings, JobOrderSettings>(); Mapper.CreateMap<JobInvoiceSettings, JobInvoiceSettings>(); Mapper.CreateMap<JobOrderInspectionRequestSettings, JobOrderInspectionRequestSettings>(); Mapper.CreateMap<JobOrderInspectionSettings, JobOrderInspectionSettings>(); Mapper.CreateMap<JobReceiveQASettings, JobReceiveQASettings>(); Mapper.CreateMap<JobReceiveSettings, JobReceiveSettings>(); Mapper.CreateMap<JobOrderLine, JobOrderLine>(); Mapper.CreateMap<JobReceiveLine, JobReceiveLine>(); Mapper.CreateMap<JobOrderHeaderCharge, JobOrderHeaderCharge>(); Mapper.CreateMap<JobOrderLineCharge, JobOrderLineCharge>(); Mapper.CreateMap<JobOrderCancelLine, JobOrderCancelLine>(); Mapper.CreateMap<JobInvoiceLine, JobInvoiceLine>(); Mapper.CreateMap<JobInvoiceLineCharge, JobInvoiceLineCharge>(); Mapper.CreateMap<JobInvoiceHeaderCharge, JobInvoiceHeaderCharge>(); Mapper.CreateMap<JobReturnLine, JobReturnLine>(); Mapper.CreateMap<PersonRegistration, PersonRegistration>(); Mapper.CreateMap<LedgerAccount, LedgerAccount>(); Mapper.CreateMap<PersonAddress, PersonAddress>(); Mapper.CreateMap<Person, Person>(); Mapper.CreateMap<BusinessEntity, BusinessEntity>(); Mapper.CreateMap<JobWorker, JobWorker>(); Mapper.CreateMap<StockLine, StockLine>(); Mapper.CreateMap<JobOrderRateAmendmentLine, JobOrderRateAmendmentLine>(); Mapper.CreateMap<JobInvoiceRateAmendmentLine, JobInvoiceRateAmendmentLine>(); Mapper.CreateMap<StockHeader, StockHeader>(); Mapper.CreateMap<JobInvoiceHeader, JobInvoiceHeader>(); Mapper.CreateMap<JobReceiveHeader, JobReceiveHeader>(); Mapper.CreateMap<JobInvoiceLineIndexViewModel,JobInvoiceLine>(); Mapper.CreateMap<JobReceiveLineViewModel, JobReceiveLine>(); Mapper.CreateMap<JobOrderCancelHeader, JobOrderCancelHeader>(); Mapper.CreateMap<JobOrderCancelLineViewModel, JobOrderCancelLine>(); Mapper.CreateMap<JobOrderAmendmentHeader, JobOrderAmendmentHeader>(); Mapper.CreateMap<JobOrderRateAmendmentLineViewModel, JobOrderRateAmendmentLine>(); Mapper.CreateMap<JobInvoiceAmendmentHeader, JobInvoiceAmendmentHeader>(); Mapper.CreateMap<JobInvoiceRateAmendmentLineViewModel, JobInvoiceRateAmendmentLine>(); Mapper.CreateMap<JobReceiveLineViewModel, JobReceiveLine>(); Mapper.CreateMap<JobReturnLineIndexViewModel, JobReturnLine>(); Mapper.CreateMap<JobOrderHeader, JobOrderHeader>(); Mapper.CreateMap<JobOrderLineViewModel, JobOrderLine>(); Mapper.CreateMap<JobOrderHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderHeader, DocumentUniqueId>(); Mapper.CreateMap<JobInvoiceHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobInvoiceHeader, DocumentUniqueId>(); Mapper.CreateMap<JobInvoiceAmendmentHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobInvoiceAmendmentHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderAmendmentHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderAmendmentHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderCancelHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderCancelHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionHeader, DocumentUniqueId>(); Mapper.CreateMap<JobReceiveQAHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobReceiveQAHeader, DocumentUniqueId>(); Mapper.CreateMap<JobReceiveQAHeader, JobReceiveQAAttributeViewModel>(); Mapper.CreateMap<JobReceiveQAAttributeViewModel, JobReceiveQAHeader>(); Mapper.CreateMap<JobReceiveQAPenalty, JobReceiveQAPenaltyViewModel>(); Mapper.CreateMap<JobReceiveQAPenaltyViewModel, JobReceiveQAPenalty>(); Mapper.CreateMap<JobOrderInspectionRequestCancelHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionRequestCancelHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionRequestHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionRequestHeader, DocumentUniqueId>(); Mapper.CreateMap<JobReceiveHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobReceiveHeader, DocumentUniqueId>(); Mapper.CreateMap<JobReturnHeaderViewModel, DocumentUniqueId>(); Mapper.CreateMap<JobReturnHeader, DocumentUniqueId>(); Mapper.CreateMap<JobOrderInspectionRequestHeader, JobOrderInspectionRequestHeaderViewModel>(); Mapper.CreateMap<JobOrderInspectionRequestHeaderViewModel, JobOrderInspectionRequestHeader>(); Mapper.CreateMap<JobOrderInspectionRequestLine, JobOrderInspectionRequestLineViewModel>(); Mapper.CreateMap<JobOrderInspectionRequestLineViewModel, JobOrderInspectionRequestLine>(); Mapper.CreateMap<JobOrderInspectionRequestSettings, JobOrderInspectionRequestSettingsViewModel>(); Mapper.CreateMap<JobOrderInspectionRequestSettingsViewModel, JobOrderInspectionRequestSettings>(); Mapper.CreateMap<JobOrderInspectionSettings, JobOrderInspectionSettingsViewModel>(); Mapper.CreateMap<JobOrderInspectionSettingsViewModel, JobOrderInspectionSettings>(); Mapper.CreateMap<JobOrderInspectionRequestHeader, JobOrderInspectionRequestHeader>(); Mapper.CreateMap<JobOrderInspectionRequestLine, JobOrderInspectionRequestLine>(); Mapper.CreateMap<JobOrderInspectionRequestCancelHeader, JobOrderInspectionRequestCancelHeaderViewModel>(); Mapper.CreateMap<JobOrderInspectionRequestCancelHeaderViewModel, JobOrderInspectionRequestCancelHeader>(); Mapper.CreateMap<JobOrderInspectionRequestCancelLine, JobOrderInspectionRequestCancelLineViewModel>(); Mapper.CreateMap<JobOrderInspectionRequestCancelLineViewModel, JobOrderInspectionRequestCancelLine>(); Mapper.CreateMap<JobOrderInspectionRequestCancelHeader, JobOrderInspectionRequestCancelHeader>(); Mapper.CreateMap<JobOrderInspectionRequestCancelLine, JobOrderInspectionRequestCancelLine>(); Mapper.CreateMap<JobOrderInspectionHeader, JobOrderInspectionHeaderViewModel>(); Mapper.CreateMap<JobOrderInspectionHeaderViewModel, JobOrderInspectionHeader>(); Mapper.CreateMap<JobOrderInspectionLine, JobOrderInspectionLineViewModel>(); Mapper.CreateMap<JobOrderInspectionLineViewModel, JobOrderInspectionLine>(); Mapper.CreateMap<JobOrderInspectionHeader, JobOrderInspectionHeader>(); Mapper.CreateMap<JobOrderInspectionLine, JobOrderInspectionLine>(); Mapper.CreateMap<JobReceiveQAHeader, JobReceiveQAHeaderViewModel>(); Mapper.CreateMap<JobReceiveQAHeaderViewModel, JobReceiveQAHeader>(); Mapper.CreateMap<JobReceiveQALine, JobReceiveQALineViewModel>(); Mapper.CreateMap<JobReceiveQALineViewModel, JobReceiveQALine>(); Mapper.CreateMap<JobReceiveQALine, JobReceiveQAAttributeViewModel>(); Mapper.CreateMap<JobReceiveQAAttributeViewModel, JobReceiveQALine>(); Mapper.CreateMap<JobReceiveQAHeader, JobReceiveQAHeader>(); Mapper.CreateMap<JobReceiveQALine, JobReceiveQALine>(); Mapper.CreateMap<JobReceiveQASettings, JobReceiveQASettingsViewModel>(); Mapper.CreateMap<JobReceiveQASettingsViewModel, JobReceiveQASettings>(); Mapper.CreateMap<JobInvoiceReturnHeader, JobInvoiceReturnHeader>(); Mapper.CreateMap<JobInvoiceReturnLine, JobInvoiceReturnLine>(); Mapper.CreateMap<JobInvoiceReturnHeaderViewModel, JobReturnHeader>(); Mapper.CreateMap<JobInvoiceReturnLineViewModel, JobInvoiceReturnLine>(); Mapper.CreateMap<JobInvoiceReturnLine, JobInvoiceReturnLineViewModel>(); Mapper.CreateMap<JobInvoiceReturnLineViewModel, JobReturnLine>(); Mapper.CreateMap<JobReturnLine, JobInvoiceReturnLineViewModel>(); Mapper.CreateMap<JobInvoiceReturnLine, JobReturnLine>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace ShoppingCart.ViewModels { public class CategoryViewModel { [JsonProperty(PropertyName = "id")] public int Id { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace Gruzer.Data.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Places", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Address = table.Column<string>(nullable: true), City = table.Column<string>(nullable: true), Coordinate = table.Column<string>(nullable: true), IsWeekend = table.Column<bool>(nullable: false), Name = table.Column<string>(nullable: true), WorkTimeEnd = table.Column<TimeSpan>(nullable: true), WorkTimeStart = table.Column<TimeSpan>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Places", x => x.Id); }); migrationBuilder.CreateTable( name: "CargoTypes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_CargoTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "PackageTypes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_PackageTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Role", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Role", x => x.Id); }); migrationBuilder.CreateTable( name: "Companies", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Address = table.Column<string>(nullable: true), BIK = table.Column<string>(nullable: true), BankAccount = table.Column<string>(nullable: true), INN = table.Column<string>(nullable: true), KPP = table.Column<string>(nullable: true), Management = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), PlaceId = table.Column<int>(nullable: true), Raiting = table.Column<double>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Companies", x => x.Id); table.ForeignKey( name: "FK_Companies_Places_PlaceId", column: x => x.PlaceId, principalTable: "Places", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Customers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Address = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), PlaceId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Customers", x => x.Id); table.ForeignKey( name: "FK_Customers_Places_PlaceId", column: x => x.PlaceId, principalTable: "Places", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Shipments", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CargoTypeId = table.Column<int>(nullable: true), DeliveryPointAId = table.Column<int>(nullable: true), DeliveryPointBId = table.Column<int>(nullable: true), Dimension = table.Column<string>(nullable: true), Document = table.Column<byte[]>(nullable: true), FinishDate = table.Column<DateTime>(nullable: false), PackageTypeId = table.Column<int>(nullable: true), PlannedFinishDate = table.Column<DateTime>(nullable: false), Price = table.Column<decimal>(nullable: false), StartDate = table.Column<DateTime>(nullable: false), Value = table.Column<double>(nullable: false), Weight = table.Column<double>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Shipments", x => x.Id); table.ForeignKey( name: "FK_Shipments_CargoTypes_CargoTypeId", column: x => x.CargoTypeId, principalTable: "CargoTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Shipments_Places_DeliveryPointAId", column: x => x.DeliveryPointAId, principalTable: "Places", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Shipments_Places_DeliveryPointBId", column: x => x.DeliveryPointBId, principalTable: "Places", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Shipments_PackageTypes_PackageTypeId", column: x => x.PackageTypeId, principalTable: "PackageTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), Password = table.Column<string>(nullable: true), RoleId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); table.ForeignKey( name: "FK_Users_Role_RoleId", column: x => x.RoleId, principalTable: "Role", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Transports", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CompanyId = table.Column<int>(nullable: true), Document = table.Column<byte[]>(nullable: true), InTransit = table.Column<bool>(nullable: false), Make = table.Column<string>(nullable: true), Model = table.Column<string>(nullable: true), Number = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Transports", x => x.Id); table.ForeignKey( name: "FK_Transports_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CompanyId = table.Column<int>(nullable: true), CustomerId = table.Column<int>(nullable: true), DateCreate = table.Column<DateTime>(nullable: false), ShipmentId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); table.ForeignKey( name: "FK_Orders_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Customers_CustomerId", column: x => x.CustomerId, principalTable: "Customers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Shipments_ShipmentId", column: x => x.ShipmentId, principalTable: "Shipments", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Drivers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CompanyId = table.Column<int>(nullable: true), DrivingLicence = table.Column<byte[]>(nullable: true), Experience = table.Column<int>(nullable: false), MedicalRecord = table.Column<byte[]>(nullable: true), Name = table.Column<string>(nullable: true), Pasport = table.Column<byte[]>(nullable: true), Phone = table.Column<string>(nullable: true), SanilaryRegulations = table.Column<string>(nullable: true), TransportDocument = table.Column<byte[]>(nullable: true), TransportId = table.Column<int>(nullable: true), TransportRegistration = table.Column<byte[]>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Drivers", x => x.Id); table.ForeignKey( name: "FK_Drivers_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Drivers_Transports_TransportId", column: x => x.TransportId, principalTable: "Transports", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Companies_PlaceId", table: "Companies", column: "PlaceId"); migrationBuilder.CreateIndex( name: "IX_Drivers_CompanyId", table: "Drivers", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Drivers_TransportId", table: "Drivers", column: "TransportId", unique: true); migrationBuilder.CreateIndex( name: "IX_Transports_CompanyId", table: "Transports", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Customers_PlaceId", table: "Customers", column: "PlaceId"); migrationBuilder.CreateIndex( name: "IX_Orders_CompanyId", table: "Orders", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Orders_CustomerId", table: "Orders", column: "CustomerId"); migrationBuilder.CreateIndex( name: "IX_Orders_ShipmentId", table: "Orders", column: "ShipmentId", unique: true); migrationBuilder.CreateIndex( name: "IX_Shipments_CargoTypeId", table: "Shipments", column: "CargoTypeId"); migrationBuilder.CreateIndex( name: "IX_Shipments_DeliveryPointAId", table: "Shipments", column: "DeliveryPointAId"); migrationBuilder.CreateIndex( name: "IX_Shipments_DeliveryPointBId", table: "Shipments", column: "DeliveryPointBId"); migrationBuilder.CreateIndex( name: "IX_Shipments_PackageTypeId", table: "Shipments", column: "PackageTypeId"); migrationBuilder.CreateIndex( name: "IX_Users_RoleId", table: "Users", column: "RoleId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Drivers"); migrationBuilder.DropTable( name: "Orders"); migrationBuilder.DropTable( name: "Users"); migrationBuilder.DropTable( name: "Transports"); migrationBuilder.DropTable( name: "Customers"); migrationBuilder.DropTable( name: "Shipments"); migrationBuilder.DropTable( name: "Role"); migrationBuilder.DropTable( name: "Companies"); migrationBuilder.DropTable( name: "CargoTypes"); migrationBuilder.DropTable( name: "PackageTypes"); migrationBuilder.DropTable( name: "Places"); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Ardalis.ApiEndpoints; using AutoMapper; using BlazorShared.Models.Schedule; using FrontDesk.Core.Aggregates; using Microsoft.AspNetCore.Mvc; using PluralsightDdd.SharedKernel.Interfaces; using Swashbuckle.AspNetCore.Annotations; namespace FrontDesk.Api.ScheduleEndpoints { public class List : BaseAsyncEndpoint .WithRequest<ListScheduleRequest> .WithResponse<ListScheduleResponse> { private readonly IRepository _repository; private readonly IMapper _mapper; public List(IRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } [HttpGet("api/schedules")] [SwaggerOperation( Summary = "List Schedules", Description = "List Schedules", OperationId = "schedules.List", Tags = new[] { "ScheduleEndpoints" }) ] public override async Task<ActionResult<ListScheduleResponse>> HandleAsync([FromQuery] ListScheduleRequest request, CancellationToken cancellationToken) { var response = new ListScheduleResponse(request.CorrelationId()); var schedules = await _repository.ListAsync<Schedule, Guid>(); if (schedules is null) return NotFound(); response.Schedules = _mapper.Map<List<ScheduleDto>>(schedules); response.Count = response.Schedules.Count; return Ok(response); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI.MoneyXChange.Models; namespace WebAPI.MoneyXChange.Services.Contracts { public interface IOperationService { Task<CurrencyRate> FindCurrencyRate(DateTime date, int currencyFrom, int currencyTo); double ExchangeCurrency(DateTime date, int currencyFrom, int currencyTo, double currencyValue); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WebApp1 { public partial class Form1 : Form { private int counter = 0; private int timerInterval = 10000; private List<String> URLs = new List<string>() { "www.google.com", "www.yandex.ru", "www.wikipedia.org"}; public Form1() { InitializeComponent(); webBrowser1.ScriptErrorsSuppressed = true; timer1.Interval = timerInterval; timer1.Start(); } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { } private void timer1_Tick(object sender, EventArgs e) { webBrowser1.Navigate(URLs[counter]); counter = ++counter % URLs.Count; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace pjank.BossaAPI { /// <summary> /// Lista raportów z wykonania kolejnych transakcji dla naszego zlecenia. /// </summary> public class BosOrderTradeReports : IEnumerable<BosOrderTradeReport> { private List<BosOrderTradeReport> list = new List<BosOrderTradeReport>(); public int Count { get { return list.Count; } } public BosOrderTradeReport this[int index] { get { return list[index]; } } public IEnumerator<BosOrderTradeReport> GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // aktualizacja danych na liście po odebraniu ich z sieci internal void Update(DTO.OrderTradeData data) { list.Add(new BosOrderTradeReport(data)); } } }
using System; using System.Windows; using System.Windows.Forms.Integration; namespace IKriv.Windows.Integration { public class SizeToContentWinFormsHost : WindowsFormsHost { private readonly System.Windows.Forms.UserControl _control; public SizeToContentWinFormsHost(System.Windows.Forms.UserControl control) { _control = control; Child = control; control.SizeChanged += OnControlSizeChanged; } void OnControlSizeChanged(object sender, EventArgs e) { if (Visibility != Visibility.Visible) return; InvalidateMeasure(); } protected override Size MeasureOverride(Size constraint) { var defaultSize = base.MeasureOverride(constraint); var source = PresentationSource.FromVisual(this); if (source == null) return defaultSize; var transformFromDevice = source.CompositionTarget.TransformFromDevice; var vector = new Vector(_control.Size.Width, _control.Size.Height); var controlSizeVector = transformFromDevice.Transform(vector); var controlSize = new Size(controlSizeVector.X, controlSizeVector.Y); return controlSize; } } }
namespace Sentry.EntityFramework.Tests; public class TestDbContext : DbContext { public TestDbContext(DbConnection connection, bool ownsConnection) : base(connection, ownsConnection) { } public virtual DbSet<TestData> TestTable { get; set; } public class TestData { [Key] public int Id { get; set; } public string AColumn { get; set; } [Required] public string RequiredColumn { get; set; } } }
using Stock_Exchange_Analyzer.Data_Storage; using System; using System.Windows.Forms; using Stock_Exchange_Analyzer.Properties; namespace Stock_Exchange_Analyzer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Portfolio mainPortfolio = null; if (Settings.Default.loadDefaultPortfolio) { try { mainPortfolio = Portfolio.loadPortfolio(Settings.Default.defaultPortfolioPath); } catch { mainPortfolio = null; Settings.Default.loadDefaultPortfolio = false; Settings.Default.Save(); } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main_Menu(ref mainPortfolio)); } } }
namespace DChild.Gameplay { public interface IJump { bool Jump(bool isPressed); } }
using System; using System.Text; namespace Base64Translator { class Base64Translator { /// <exception cref="FormatException"></exception> public static string EncryptBase64(string input, Encoding encoding) { byte[] inBytes = encoding.GetBytes(input); return Convert.ToBase64String(inBytes); } /// <exception cref="FormatException"></exception> public static string DecryptBase64(string input, Encoding encoding) { byte[] inBytes = Convert.FromBase64String(input); return encoding.GetString(inBytes); } } }
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace Funding.Data.Migrations { public partial class up : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Name", table: "Tags", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Projects", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ImageUrl", table: "Projects", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Description", table: "Projects", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Title", table: "Messages", maxLength: 100, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Content", table: "Messages", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "LastName", table: "AspNetUsers", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "FirstName", table: "AspNetUsers", maxLength: 2400, nullable: false, oldClrType: typeof(string), oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Name", table: "Tags", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "Name", table: "Projects", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "ImageUrl", table: "Projects", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "Description", table: "Projects", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "Title", table: "Messages", nullable: true, oldClrType: typeof(string), oldMaxLength: 100); migrationBuilder.AlterColumn<string>( name: "Content", table: "Messages", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "LastName", table: "AspNetUsers", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); migrationBuilder.AlterColumn<string>( name: "FirstName", table: "AspNetUsers", nullable: true, oldClrType: typeof(string), oldMaxLength: 2400); } } }
using OnboardingSIGDB1.Domain.Interfaces; using OnboardingSIGDB1.Domain.Notifications; using System.Linq; using System.Threading.Tasks; namespace OnboardingSIGDB1.Domain.Empresas.Validators { public class ValidadorDeEmpresaDuplicada: IValidadorDeEmpresaDuplicada { private readonly IEmpresaRepository _empresaRepository; private readonly NotificationContext _notificationContext; public ValidadorDeEmpresaDuplicada(IEmpresaRepository empresaRepository, NotificationContext notificationContext) { _empresaRepository = empresaRepository; _notificationContext = notificationContext; } public async Task Valid(Empresa empresa) { var empresas = await _empresaRepository.Get(emp => emp.Cnpj.Equals(empresa.Cnpj)); if (empresas.Any()) { _notificationContext.AddNotification(new Notification("CnpjDuplicado", "Já existe uma empresa cadastrada com esse CNPJ")); } } } }
namespace TripDestination.Web.MVC.Areas.Admin.Controllers { using Common.Infrastructure.Mapping; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using MVC.Controllers; using Services.Data.Contracts; using System.Web.Mvc; using ViewModels; public class NotificationTypeAdminController : BaseController { private readonly INotificationTypeServices notificationTypeServices; public NotificationTypeAdminController(INotificationTypeServices notificationTypeServices) { this.notificationTypeServices = notificationTypeServices; } public ActionResult Index() { return this.View(); } public ActionResult NotificationType_Read([DataSourceRequest]DataSourceRequest request) { var result = this.notificationTypeServices .GetAll() .To<NotificationTypeAdminViewModel>() .ToDataSourceResult(request); return this.Json(result); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }