コード例 #1
0
        private void FormLoad_Handler(object sender, EventArgs e)
        {
            // Get turnos
            loadTurnos();

            // Execute SQL query to get Docente rows
            SqlCommand    cmd    = new SqlCommand("SELECT * FROM vw_NaoDocentes", cn);
            SqlDataReader reader = cmd.ExecuteReader();
            // Create list of Objects given the query results
            List <NaoDocente> tuplos = new List <NaoDocente>();

            while (reader.Read())
            {
                NaoDocente d = new NaoDocente();
                d.nmec      = Int32.Parse(reader["NMec"].ToString());
                d.nome      = reader["nome"].ToString();
                d.salario   = Double.Parse(reader["salario"].ToString());
                d.telemovel = Int32.Parse(reader["telemovel"].ToString());
                d.email     = reader["emailComposed"].ToString();
                d.turno     = getTurno(Int32.Parse(reader["turno"].ToString()));
                tuplos.Add(d);
                counter++;
            }

            // Close reader
            reader.Close();

            // ObjectListView
            // Add Objects to list view
            listObjects.SetObjects(tuplos);

            // Update stats
            updateStats();
        }
コード例 #2
0
        private void editObject()
        {
            // Get Object
            if (listObjects.Items.Count == 0 | current < 0)
            {
                return;
            }
            NaoDocente f = (NaoDocente)listObjects.SelectedObjects[0];

            // Set textboxes value
            panelFormFieldNMec.Text     = f.nmec.ToString();
            panelFormFieldNome.Text     = f.nome;
            panelFormFieldContacto.Text = f.telemovel.ToString();
            panelFormFieldEmail.Text    = f.email;
            panelFormFieldSalario.Text  = f.salario.ToString();
            panelFormFieldTurno.Text    = f.turno.str;
            // Disable fields not changable
            panelFormFieldNMec.Enabled = false;
            // Set title and description
            panelFormTitulo.Text    = "Editar funcionário " + f.nmec.ToString();
            panelFormDescricao.Text = "Altere os dados e submita o formulário";
            panelFormButton.Text    = "Submeter";
            // Make panel visible
            if (!panelForm.Visible)
            {
                panelForm.Visible = true;
            }
        }
コード例 #3
0
 // Constructor
 public NaoDocenteHorario(SqlConnection cn, NaoDocente nd, Form f)
 {
     this.cn       = cn;
     this.previous = f;
     this.nd       = nd;
     this.blocos   = new List <Bloco>();
     this.funcoes  = new List <NDFuncao>();
     InitializeComponent();
 }
コード例 #4
0
        private void panelObjectVerHorario_Click(object sender, EventArgs e)
        {
            // Get Object
            if (listObjects.Items.Count == 0 | current < 0)
            {
                return;
            }
            NaoDocente nd = (NaoDocente)listObjects.SelectedObjects[0];
            //this.Hide();
            NaoDocenteHorario f = new NaoDocenteHorario(cn, nd, this);

            f.ShowDialog();
        }
コード例 #5
0
        private void pesquisar()
        {
            // Get attribute and value fields text
            String atr = pesquisaAtributo.Text;
            String val = pesquisaTexto.Text;

            if (atr == "" || val == "")
            {
                // If one of them is empty, don't filter
                this.listObjects.ModelFilter = null;
            }
            else
            {
                // Define filtering
                this.listObjects.ModelFilter = new ModelFilter(delegate(object x) {
                    NaoDocente func = (NaoDocente)x;
                    String toFilter = "";
                    switch (atr)
                    {
                    case "Número mecanográfico":
                        toFilter = func.nmec.ToString();
                        break;

                    case "Salário":
                        toFilter = func.salario.ToString();
                        break;

                    case "Nome":
                        toFilter = func.nome;
                        break;

                    case "Contacto":
                        toFilter = func.telemovel.ToString();
                        break;

                    case "Turno":
                        toFilter = func.turno.str;
                        break;
                    }
                    if (toFilter.ToLower().Contains(val.ToLower()))
                    {
                        return(true);
                    }
                    return(false);
                });
            }
            updateStats();
            // Hide data panel (both edit and data)
            panelObject.Visible = false;
            panelForm.Visible   = false;
        }
コード例 #6
0
 // Constructor
 public NaoDocenteTurnos(SqlConnection cn, NaoDocente nd, Form f)
 {
     this.cn       = cn;
     this.previous = f;
     this.nd       = nd;
     this.blocos   = new List <Bloco>();
     this.funcoes  = new List <NDFuncao>();
     InitializeComponent();
     // ObjectListView Column groups
     // http://objectlistview.sourceforge.net/python/groupListView.html
     // ObjectListView Aditional preferences
     this.listObjects.FullRowSelect = true; //Make selection select the full row (and not only a cell)
     this.listObjects.SelectedIndex = 0;    //Make the first row selected ad default
     // Filtering
     this.listObjects.UseFiltering = true;  // Activate filtering (for search porpuses)
 }
コード例 #7
0
 // Constructor
 public NaoDocentes(SqlConnection cn, Form f)
 {
     this.cn       = cn;
     this.previous = f;
     this.turnos   = new List <Turno>();
     InitializeComponent();
     // ObjectListView Column groups
     // http://objectlistview.sourceforge.net/python/groupListView.html
     this.nmec.GroupKeyGetter = delegate(object rowObject) {
         // When the same is returned by every object, all of them are put together in one group
         return("Número mecanográfico");
     };
     this.nome.GroupKeyGetter = delegate(object rowObject)
     {
         return("Nome");
     };
     this.salario.GroupKeyGetter = delegate(object rowObject) {
         // Group salaries by the integer value of it
         NaoDocente func = (NaoDocente)rowObject;
         return(func.salario.ToString().Split(',')[0]);
     };
     this.tel.GroupKeyGetter = delegate(object rowObject) {
         // Group phones by the first two digits (phone company indicator)
         NaoDocente func = (NaoDocente)rowObject;
         if (func.telemovel.ToString().Length > 2)
         {
             return(func.telemovel.ToString().Substring(0, 2));
         }
         return("Outros");
     };
     this.email.GroupKeyGetter = delegate(object rowObject) {
         // Group emails by domain (text after @ symbol)
         NaoDocente func = (NaoDocente)rowObject;
         return(func.email.Split('@')[1]);
     };
     this.turno.GroupKeyGetter = delegate(object rowObject) {
         // Group emails by domain (text after @ symbol)
         NaoDocente func = (NaoDocente)rowObject;
         return("Das " + func.turno.horaInicio.ToString(@"hh", null) + " às " + func.turno.horaFim.ToString(@"hh", null));
     };
     // ObjectListView Aditional preferences
     this.listObjects.FullRowSelect = true; //Make selection select the full row (and not only a cell)
     this.listObjects.SelectedIndex = 0;    //Make the first row selected ad default
     // Filtering
     pesquisaAtributo.SelectedIndex = 0;    // Set atribute combo box selected index to xero as default
     this.listObjects.UseFiltering  = true; // Activate filtering (for search porpuses)
 }
コード例 #8
0
ファイル: Blocos.cs プロジェクト: gmatosferreira/dbproject
        //  Methods

        private void loadNaoDocentes()
        {
            // Execute SQL query to get Docente rows
            SqlCommand    cmd    = new SqlCommand("SELECT * FROM vw_NaoDocentes", cn);
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                NaoDocente d = new NaoDocente();
                d.nmec = Int32.Parse(reader["NMec"].ToString());
                d.nome = reader["nome"].ToString();
                panelFormFieldSupervisor.Items.Add(d.ToString());
                naodocentes.Add(d);
                counter++;
            }

            // Close reader
            reader.Close();
        }
コード例 #9
0
        private void showObject()
        {
            // Get Object
            if (listObjects.Items.Count == 0 | current < 0)
            {
                return;
            }
            NaoDocente f = (NaoDocente)listObjects.SelectedObjects[0];

            // Set labels values
            panelObjectTitulo.Text    = f.nome;
            panelObjectSubtitulo.Text = f.nmec.ToString();
            // Show panel
            if (!panelObject.Visible)
            {
                panelObject.Visible = true;
            }
            panelForm.Visible = false;
        }
コード例 #10
0
ファイル: Blocos.cs プロジェクト: gmatosferreira/dbproject
        private void submitForm(Bloco bloco)
        {
            /*
             * If submition for edit t!=null
             * If new submition t==null
             */
            bool edit = (bloco != null);
            // Get form data
            String     nome        = panelFormFieldNome.Text;
            String     coordenadas = panelFormFieldCoordenadas.Text;
            BlocoTipo  blocotipo   = getBlocoTipo(panelFormFieldTipo.Text);
            NaoDocente supervisor  = getNaoDocente(panelFormFieldSupervisor.Text);
            // Create command
            String commandText = "INSERT INTO GestaoEscola.Bloco VALUES (@Coordenadas, @Nome, @Tipo, @Supervisor)";

            if (edit)
            {
                commandText = "UPDATE GestaoEscola.Bloco SET nome = @Nome, tipo = @Tipo, supervisor = @Supervisor WHERE coordenadas = @Coordenadas";
            }
            SqlCommand command = new SqlCommand(commandText, cn);

            // Add vars
            command.Parameters.Add("@Coordenadas", SqlDbType.VarChar).Value = coordenadas;
            command.Parameters.Add("@Nome", SqlDbType.VarChar).Value        = nome;
            command.Parameters.Add("@Tipo", SqlDbType.Int).Value            = blocotipo.codigo;
            command.Parameters.Add("@Supervisor", SqlDbType.Int).Value      = supervisor.nmec;
            // 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("Violation of PRIMARY KEY constraint", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        errorMessage = "Não pode inserir um bloco nas coordenadas de um já existente!";
                        break;
                    }
                }
                MessageBox.Show(
                    errorMessage + "\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
                    bloco             = new Bloco();
                    bloco.coordenadas = coordenadas;
                    bloco.nome        = nome;
                    bloco.tipo        = blocotipo;
                    bloco.supervisor  = supervisor;
                    listObjects.AddObject(bloco);
                }
                else
                {
                    // Get object on interface list and change attributes
                    bloco.nome       = nome;
                    bloco.tipo       = blocotipo;
                    bloco.supervisor = supervisor;
                }
                // SHow feedback to user
                String successMessage = "O bloco foi adicionado com sucesso!";
                if (edit)
                {
                    successMessage = "O bloco foi atualizado 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
                    );
            }
        }
コード例 #11
0
        private void submitForm(NaoDocente ndocente)
        {
            bool edit = (ndocente != null);

            // Get form data
            int    nmec         = Int32.Parse(panelFormFieldNMec.Text);
            String nome         = panelFormFieldNome.Text;
            Double salario      = Double.Parse(panelFormFieldSalario.Text);
            int    telemovel    = Int32.Parse(panelFormFieldContacto.Text);
            String emailPrefixo = panelFormFieldEmail.Text.Split('@')[0];
            String emailDominio = panelFormFieldEmail.Text.Split('@')[1];
            Turno  turno        = getTurno(panelFormFieldTurno.Text);

            // Create command
            String     commandText = "pr_NaoDocentes";
            SqlCommand command     = new SqlCommand(commandText, cn);

            command.CommandType = CommandType.StoredProcedure;
            // Add vars
            command.Parameters.Add("@NMec", SqlDbType.Int);
            command.Parameters["@NMec"].Value = nmec;
            command.Parameters.Add("@Nome", SqlDbType.VarChar);
            command.Parameters["@Nome"].Value = nome;
            command.Parameters.Add("@Telemovel", SqlDbType.Int);
            command.Parameters["@Telemovel"].Value = telemovel;
            command.Parameters.Add("@Email", SqlDbType.VarChar);
            command.Parameters["@Email"].Value = emailPrefixo;
            command.Parameters.Add("@EmailDominio", SqlDbType.VarChar);
            command.Parameters["@EmailDominio"].Value = emailDominio;
            command.Parameters.Add("@Salario", SqlDbType.Money);
            command.Parameters["@Salario"].Value = salario;
            command.Parameters.Add("@Turno", SqlDbType.Int);
            command.Parameters["@Turno"].Value = turno.codigo;
            command.Parameters.Add("@Edit", SqlDbType.Bit);
            command.Parameters["@Edit"].Value = 0;
            if (edit)
            {
                command.Parameters["@Edit"].Value = 1;
            }
            // Return value stuff
            var returnParameter = command.Parameters.Add("@ReturnVal", SqlDbType.Int);

            returnParameter.Direction = ParameterDirection.ReturnValue;
            // Execute query
            int rowsAffected = 0;
            int returnValue;

            try
            {
                rowsAffected = command.ExecuteNonQuery();
                returnValue  = (int)returnParameter.Value;
                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("Já existe uma pessoa com o email", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        errorMessage = ex.Errors[i].Message;
                        break;
                    }
                    if (ex.Errors[i].Message.IndexOf("Já existe uma pessoa com o número de telemóvel fornecido", 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 (returnValue == 1)
            {
                // If add operation, construct object (was null)
                if (!edit)
                {
                    ndocente = new NaoDocente();
                }
                ndocente.nmec      = nmec;
                ndocente.nome      = nome;
                ndocente.email     = emailPrefixo + "@" + emailDominio;
                ndocente.telemovel = telemovel;
                ndocente.salario   = salario;
                ndocente.turno     = turno;
                if (!edit)
                {
                    listObjects.AddObject(ndocente);
                }
                // SHow feedback to user
                String successMessage = "O não docente foi adicionado com sucesso!";
                if (edit)
                {
                    successMessage = "O não docente foi editado 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
            {
                String messageError = "Ocorreu um erro, verifique que preencheu todos os dados corretamente e tente novamente!";
                if (returnValue == -2)
                {
                    messageError = "Já existe uma pessoa na base de dados com esse número mecanográfico!";
                }
                else if (returnValue == -3 || returnValue == -4)
                {
                    messageError = "Ocorreu um erro interno na base de dados! Tente novamente.";
                }
                MessageBox.Show(
                    messageError,
                    "Erro!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );
            }
        }
コード例 #12
0
        private void deleteObject()
        {
            // Get Object
            if (listObjects.Items.Count == 0 | current < 0)
            {
                return;
            }
            NaoDocente f         = (NaoDocente)listObjects.SelectedObjects[0];
            int        itemIndex = listObjects.SelectedIndex;
            // Confirm delete
            DialogResult msgb = MessageBox.Show("Tem a certeza que quer eliminar o funcionário " + f.nmec.ToString() + "?", "Operação delicada", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            if (msgb == DialogResult.No)
            {
                return;
            }
            // Delete tuple on db
            String     commandText = "DELETE FROM GestaoEscola.NaoDocente WHERE NMec = @ID";
            SqlCommand command     = new SqlCommand(commandText, cn);

            // Add vars
            command.Parameters.Add("@ID", SqlDbType.Int);
            command.Parameters["@ID"].Value = f.nmec;

            // Execute query
            int rowsAffected = 0;

            try
            {
                rowsAffected = command.ExecuteNonQuery();
                Console.WriteLine(String.Format("rowsAffected {0}", rowsAffected));
            }
            catch (SqlException ex)
            {
                String errorMessage = "Ocorreu um erro, tente novamente!";
                for (int i = 0; i < ex.Errors.Count; i++)
                {
                    if (ex.Errors[i].Message.IndexOf("O funcionário não pode ser eliminado enquanto for supervisor", 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 successful query
            if (rowsAffected == 3)
            {
                // Remove object from interface list
                listObjects.Items.RemoveAt(itemIndex);
                // Show user feedback
                MessageBox.Show(
                    "O tuplo foi eliminado com sucesso da base de dados!",
                    "Sucesso!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information
                    );
                // Update stats
                updateStats();
                // Hide panels
                panelForm.Visible   = false;
                panelObject.Visible = false;
            }
            else
            {
                MessageBox.Show(
                    "Ocorreu um erro, tente novamente!",
                    "Erro!",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );
            }
        }