private void FormLoad_Handler(object sender, EventArgs e) { // Execute SQL query to get Docente rows SqlCommand cmd = new SqlCommand("SELECT * FROM GestaoEscola.ND_Funcao", cn); SqlDataReader reader = cmd.ExecuteReader(); // Create list of Objects given the query results List <NDFuncao> tuplos = new List <NDFuncao>(); while (reader.Read()) { NDFuncao t = new NDFuncao(); t.codigo = Int32.Parse(reader["codigo"].ToString()); t.nome = reader["nome"].ToString(); if (t.codigo > lastId) { lastId = t.codigo; } tuplos.Add(t); counter++; } // Close reader reader.Close(); // ObjectListView // Add Objects to list view listObjects.SetObjects(tuplos); // Update stats updateStats(); }
private void loadFuncoes() { // Execute SQL query to get Docente rows SqlCommand cmd = new SqlCommand("SELECT * FROM GestaoEscola.ND_Funcao", cn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { NDFuncao t = new NDFuncao(); t.codigo = Int32.Parse(reader["codigo"].ToString()); t.nome = reader["nome"].ToString(); funcoes.Add(t); } // Close reader reader.Close(); }
private void showObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } NDFuncao f = (NDFuncao)listObjects.SelectedObjects[0]; // Set labels values panelObjectTitulo.Text = "Função"; panelObjectSubtitulo.Text = f.nome; // Show panel if (!panelObject.Visible) { panelObject.Visible = true; } panelForm.Visible = false; }
private void editObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } NDFuncao f = (NDFuncao)listObjects.SelectedObjects[0]; // Set textboxes value panelFormFieldNome.Text = f.nome; // Set title and description panelFormTitulo.Text = "Editar função"; panelFormDescricao.Text = "Altere os dados e submita o formulário"; panelFormButton.Text = "Submeter"; // Make panel visible if (!panelForm.Visible) { panelForm.Visible = true; } }
private void submitForm(NDTrabalhaBloco ndtb) { /* * If submition for edit t!=null * If new submition t==null */ bool edit = (ndtb != null); // Get form data TimeSpan horaInicio = TimeSpan.Parse(panelFormFieldHoraInicio.Text); TimeSpan horaFim = TimeSpan.Parse(panelFormFieldHoraFim.Text); Bloco bloco = getBlocoByNome(panelFormFieldBloco.Text); NDFuncao funcao = getFuncao(panelFormFieldFuncao.Text); // Create command bool biblioteca = bloco.nome.Substring(0, 5).Contains("Bibli"); String commandText = "INSERT INTO GestaoEscola.ND_trabalha_Bloco VALUES (@IDBloco, @NMec, @CodFuncao, @HoraInicio, @HoraFim)"; if (biblioteca) { commandText = "INSERT INTO GestaoEscola.ND_trabalha_Biblioteca VALUES (@IDBloco, @NMec, @CodFuncao, @HoraInicio, @HoraFim)"; } if (edit) { if (ndtb.bloco.nome.Substring(0, 5).Equals("Bibli") && !biblioteca || ndtb.bloco.nome.Substring(0, 5).Equals("Bloco") && biblioteca) { MessageBox.Show( "Ainda não é possível alterar o local de uma função de um bloco para uma biblioteca e vice-versa. Para fazer esta alteração deve eliminar a função atual e criar uma nova.", "Operação não suportada!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation ); return; } if (!biblioteca) { commandText = "UPDATE GestaoEscola.ND_trabalha_Bloco SET Bcoordenadas = @IDBloco, codFuncao = @CodFuncao WHERE NMec = @NMec AND horaInicio = @HoraInicio"; } else { commandText = "UPDATE GestaoEscola.ND_trabalha_Biblioteca SET biblioteca = @IDBloco, codFuncao = @CodFuncao WHERE NMec = @NMec AND horaInicio = @HoraInicio"; } } SqlCommand command = new SqlCommand(commandText, cn); // Add vars command.Parameters.Add("@IDBloco", SqlDbType.VarChar); if (!biblioteca) // Bloco { command.Parameters["@IDBloco"].Value = bloco.coordenadas.Trim(); } else // Biblioteca { command.Parameters["@IDBloco"].Value = bloco.nome.Substring(11, bloco.nome.Length - 11); } command.Parameters.Add("@NMec", SqlDbType.Int); command.Parameters["@NMec"].Value = nd.nmec; command.Parameters.Add("@CodFuncao", SqlDbType.Int); command.Parameters["@CodFuncao"].Value = funcao.codigo; command.Parameters.Add("@HoraInicio", SqlDbType.Time); command.Parameters["@HoraInicio"].Value = horaInicio; if (!edit) { command.Parameters.Add("@HoraFim", SqlDbType.Time); command.Parameters["@HoraFim"].Value = horaFim; } // Execute query int rowsAffected = 0; try { rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { String errorMessage = "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!"; for (int i = 0; i < ex.Errors.Count; i++) { if (ex.Errors[i].Message.IndexOf("A hora de início deve ser menor que a de fim", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } else if (ex.Errors[i].Message.IndexOf("O horário da nova função deve estar dentro do turno principal do funcionário", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } else if (ex.Errors[i].Message.IndexOf("O horário da nova função colide com o horário de outra função já atribuída", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } else if (ex.Errors[i].Message.IndexOf("Ocorreu um erro interno à base de dados", StringComparison.OrdinalIgnoreCase) >= 0) { errorMessage = ex.Errors[i].Message; break; } } MessageBox.Show( errorMessage + "\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If query is successful if (!edit && rowsAffected == 2 || edit && rowsAffected == 1) { // If add operation if (!edit) { // Add tuple to interface list ndtb = new NDTrabalhaBloco(); ndtb.bloco = bloco; ndtb.nd = nd; ndtb.funcao = funcao; ndtb.turno = new Turno(); ndtb.turno.horaInicio = horaInicio; ndtb.turno.horaFim = horaFim; listObjects.AddObject(ndtb); } else { // Get object on interface list and change attributes ndtb.funcao = funcao; ndtb.bloco = bloco; } // SHow feedback to user String successMessage = "A função foi adicionada com sucesso ao funcionário!"; if (edit) { successMessage = "A função foi editada com sucesso no funcionário"; } MessageBox.Show( successMessage, "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update objects displayed on interface listObjects.BuildList(true); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { MessageBox.Show( "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
private void submitForm(NDFuncao funcao) { /* * If submition for edit t!=null * If new submition t==null */ bool edit = (funcao != null); // Get form data String nome = panelFormFieldNome.Text; // Create command String commandText = "INSERT INTO GestaoEscola.ND_Funcao VALUES (@ID, @Nome)"; if (edit) { commandText = "UPDATE GestaoEscola.ND_Funcao SET nome = @Nome WHERE codigo = @ID"; } SqlCommand command = new SqlCommand(commandText, cn); // Add vars command.Parameters.Add("@ID", SqlDbType.Int); if (edit) { command.Parameters["@ID"].Value = funcao.codigo; } else { command.Parameters["@ID"].Value = lastId + 1; } command.Parameters.Add("@Nome", SqlDbType.VarChar, 15); command.Parameters["@Nome"].Value = nome; // Execute query int rowsAffected = 0; try { rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { MessageBox.Show( "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If query is successful if (rowsAffected == 1) { // If add operation if (!edit) { // Update lastId lastId++; // Add tuple to interface list funcao = new NDFuncao(); funcao.codigo = lastId; funcao.nome = nome; listObjects.AddObject(funcao); } else { // Get object on interface list and change attributes funcao.nome = nome; } // SHow feedback to user String successMessage = "A função foi adicionada com sucesso!"; if (edit) { successMessage = "A função foi editada com sucesso"; } MessageBox.Show( successMessage, "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update objects displayed on interface listObjects.BuildList(true); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { MessageBox.Show( "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
private void deleteObject() { // Get Object if (listObjects.Items.Count == 0 | current < 0) { return; } NDFuncao f = (NDFuncao)listObjects.SelectedObjects[0]; int itemIndex = listObjects.SelectedIndex; // Confirm delete DialogResult msgb = MessageBox.Show("Tem a certeza que quer eliminar esta a função '" + f.nome + "'?", "Esta operação é irreversível!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (msgb == DialogResult.No) { return; } // Create command String commandText = "pr_NDFuncaoDELETE"; SqlCommand command = new SqlCommand(commandText, cn); command.CommandType = CommandType.StoredProcedure; // Add vars command.Parameters.Add("@Codigo", SqlDbType.Int); command.Parameters["@Codigo"].Value = f.codigo; command.Parameters.Add("@Feedback", SqlDbType.VarChar, 4000).Direction = ParameterDirection.Output; // Return value stuff command.Parameters.Add("@ReturnVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; // Execute query int rowsAffected = 0; int returnValue; String returnMessage = ""; try { rowsAffected = command.ExecuteNonQuery(); returnValue = (int)command.Parameters["@ReturnVal"].Value; returnMessage = (String)command.Parameters["@Feedback"].Value; Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected)); } catch (SqlException ex) { MessageBox.Show(ex.GetType().ToString()); MessageBox.Show( "Ocorreu um erro, tente novamente!\r\n\r\n" + ex.ToString(), "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } // If successful query if (rowsAffected == 1 && returnValue == 1) { // Remove object from interface list listObjects.Items.RemoveAt(itemIndex); // Show user feedback MessageBox.Show( "O tuplo foi eliminado com sucess da base de dados!", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information ); // Update stats updateStats(); // Hide panels panelForm.Visible = false; panelObject.Visible = false; } else { String errorMessage = "Ocorreu um erro, tente novamente!"; if (returnMessage.Contains("conflicted with the REFERENCE constraint \"FK")) { errorMessage = "Esta função não pode ser eliminada enquanto estiver atribuído a um funcionário!"; } MessageBox.Show( errorMessage + "\r\n\r\n" + returnMessage, "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }