Exemple #1
0
        private void Form4_Load(object sender, EventArgs e)
        {
            if (!verifySGBDConnection())
            {
                return;
            }

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = " SELECT li.ISBN, li.titulo, li.ano, li.id_editora, ed.nome_editora , li.categoria, COUNT(li.titulo) as countTitulos " +
                              " FROM Biblioteca.Livro as li  " +
                              "                                         JOIN Biblioteca.Editora as ed ON li.id_editora = ed.id_editora " +
                              " GROUP BY li.ISBN, li.titulo, li.ano, li.id_editora, ed.nome_editora, li.categoria ";
            cmd.Connection = cn;
            SqlDataReader reader = cmd.ExecuteReader();

            listBox1.Items.Clear();

            while (reader.Read())
            {
                Emprestimo l = new Emprestimo();
                l.ISBN       = (String)reader["ISBN"];
                l.Titulo     = (String)reader["titulo"];
                l.Ano        = (int)reader["ano"];
                l.Id_editora = (int)reader["id_editora"];
                if (reader["categoria"].ToString() != "")
                {
                    l.Categoria = (String)reader["categoria"];
                }
                l.CountTilulos = (int)reader["countTitulos"];
                l.Nome_editora = (String)reader["nome_editora"];
                //l.Estado = (String)reader["estado"];
                //l.Cota = (String)reader["cota"];
                //l.Numero_exemplar = (int)reader["numero_exemplar"];
                listBox1.Items.Add(l);
            }
            listBox1.Sorted = true;
            cn.Close();
        }
Exemple #2
0
        private void buttonRemoveLivro_Click(object sender, EventArgs e)
        {
            currentLivro = listBox1.SelectedIndex;
            if (listBox1.Items.Count == 0 || currentLivro < 0)
            {
                MessageBox.Show("Escolhe um livro", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Emprestimo livro = new Emprestimo();

            livro = (Emprestimo)listBox1.Items[currentLivro];

            if (!verifySGBDConnection())
            {
                return;
            }

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "DELETE Biblioteca.Livro WHERE ISBN=@isbn ";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@isbn", livro.ISBN);
            cmd.Connection = cn;

            try
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("Livro removido com sucesso", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Não foi possivel remover o livro!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cn.Close();
            }
        }
Exemple #3
0
        private void buttonEntrega_Click(object sender, EventArgs e)
        {
            int rows = 0;

            if (listBox1.Items.Count == 0 | currentLivro < 0)
            {
                return;
            }
            Emprestimo emprestimo = new Emprestimo();

            emprestimo = (Emprestimo)listBox1.Items[currentLivro];

            if (!verifySGBDConnection())
            {
                return;
            }

            SqlCommand cmd = new SqlCommand("Biblioteca.FazerEntrega", cn);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@emprestimo", SqlDbType.Int).Value = emprestimo.N_emprestimo;

            try
            {
                rows = cmd.ExecuteNonQuery();
                MessageBox.Show("Entrega feita com Sucesso!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Não foi possivel fazer entrega!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cn.Close();
            }

            Form3_Load(sender, e);
        }
        private void btnSalvar_Click(object sender, EventArgs e)
        {
            Emprestimo emp = new Emprestimo();

            Emprestimo.NomeAlu     = txtNomeAluno.Text;
            Emprestimo.NomeLiv     = txtNomeLivro.Text;
            Emprestimo.IdAlu       = txtIdAluno.Text;
            Emprestimo.IdLiv       = txtIdLivro.Text;
            Emprestimo.Data_Retira = mskRetira.Text;
            Emprestimo.Data_Devol  = mskDevol.Text;

            emp.IncluiEmprestimo();

            txtNomeAluno.Text = "";
            txtNomeLivro.Text = "";
            txtIdAluno.Text   = "";
            txtIdLivro.Text   = "";
            mskRetira.Text    = "";
            mskDevol.Text     = "";
            lblNomeAluno.Text = "";
            lblNomeLivro.Text = "";
        }
Exemple #5
0
        private void ShowEmprestimo()
        {
            if (listBox1.Items.Count == 0 | currentLivro < 0)
            {
                return;
            }
            Emprestimo emprestimo = new Emprestimo();

            emprestimo              = (Emprestimo)listBox1.Items[currentLivro];
            textEditora.Text        = emprestimo.Nome_editora;
            textBoxDataSaida.Text   = emprestimo.Data_Saida.ToString().Split(' ')[0];
            textBoxDataEntrada.Text = emprestimo.Data_entrega.ToString().Split(' ')[0];
            textBoxDataChegada.Text = emprestimo.Data_chegada.ToString().Split(' ')[0];
            textCategoria.Text      = emprestimo.Categoria;
            if (textBoxDataChegada.Text != "")
            {
                buttonEntrega.Hide();
            }
            else
            {
                buttonEntrega.Show();
            }
        }
        private void btnCarregarEmprestimo_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog3.ShowDialog();
                Stopwatch tempo = new Stopwatch();
                tempo.Start();
                string     filename   = openFileDialog3.FileName;
                TextReader Leitor     = new StreamReader(filename, true);//Inicializa o Leitor
                int        tamanhoVet = 0;

                while (Leitor.Peek() != -1)
                {
                    //Enquanto o arquivo não acabar, o Peek não retorna -1 sendo adequando para o loop while...
                    tamanhoVet++;      //Incrementa 1 na contagem
                    Leitor.ReadLine(); //Avança uma linha no arquivo
                }

                Leitor.Close(); //Fecha o Leitor, dando acesso ao arquivo para outros programas....

                string nomeArq = openFileDialog3.FileName;
                if (!File.Exists(nomeArq))
                {
                    ;
                }
                StreamReader arqDados = new StreamReader(nomeArq);
                string       linha;
                string[]     dados;
                linha         = arqDados.ReadLine();
                vetEmprestimo = new Emprestimo[tamanhoVet];
                int pos = 0;

                while (linha != null)
                {
                    dados = linha.Split(';');


                    //Aqui o newUsuario pega o usuário sendo pesquisado por código lá no vetor dele passado por REF
                    newUsuario = PesquisaObjeto.PesquisaUsuario(int.Parse(dados[0]), vetUsuarios);

                    //Aqui o newLivro pega o Livro sendo pesquisado por código lá no vetor dele passado por REF
                    newLivro = PesquisaObjeto.PesquisaLivro(int.Parse(dados[1]), vetLivros);

                    //int codigo, string nome, int tipo, float preco_por_pagina
                    //O emprestimo é criado utilizando a referencia do livro pesquisado.... então o que acontece...
                    //não preciso criar um "novo" livro ou usuario... e sim referenciar onde eles estão na memoria
                    newEmprestimo      = new Emprestimo(ref newLivro, ref newUsuario, int.Parse(dados[2]), DateTime.Parse(dados[3]));
                    vetEmprestimo[pos] = newEmprestimo;
                    linha = arqDados.ReadLine();
                    pos  += 1;
                }
                tempo.Stop();
                MessageBox.Show("Arquivo Carregado !\n" + tempo.Elapsed.Seconds + " Segundos");
                arqDados.Close();
                //OrdenaLivro.quickSort(vetLivros);
                //MessageBox.Show("Vetor ordenado");
            }
            catch (Exception)
            {
                MessageBox.Show("Erro, tente novamente");
            }
        }
Exemple #7
0
        private void Form3_Load(object sender, EventArgs e)
        {
            if (!verifySGBDConnection())
            {
                return;
            }

            SqlCommand cmd = new SqlCommand();

            //cmd.CommandText = " DROP FUNCTION GetLivrosEmprestados " +
            //    " GO " +
            //    " CREATE FUNCTION GetLivrosEmprestados(@idCliente INT) RETURNS TABLE " +
            //    " AS " +
            //    " RETURN ( Select c.id_cliente, count(e.cliente) as numero " +
            //    " FROM Biblioteca.Cliente as c JOIN Biblioteca.Emprestimo as e ON c.id_cliente=e.cliente " +
            //    " WHERE c.id_cliente=@idCliente " +
            //    " GROUP BY c.id_cliente " +
            //    " ) " +
            //    " GO " +
            //    " SELECT * FROM GetLivrosEmprestados(5) " + //Tens de passar aqui o clienteID
            //    " GO ";
            cmd.CommandText = "SELECT * FROM Biblioteca.GetClientHistorico(@id_cliente)";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@id_cliente", c.Id);
            cmd.Connection = cn;
            SqlDataReader reader = cmd.ExecuteReader();

            listBox1.Items.Clear();

            while (reader.Read())
            {
                Emprestimo em = new Emprestimo();
                em.N_emprestimo = (int)reader["n_emprestimo"];
                em.Data_Saida   = (DateTime)reader["data_Saida"];
                em.Data_entrega = (DateTime)reader["data_entrega"];
                em.Data_Saida   = (DateTime)reader["data_Saida"];
                if (reader["data_chegada"].ToString() != "")
                {
                    em.Data_chegada = (DateTime)reader["data_chegada"];
                }
                em.ISBN   = (String)reader["ISBN"];
                em.Titulo = (String)reader["titulo"];
                em.Ano    = (int)reader["ano"];
                //e.Id_editora = (int)reader["id_editora"];
                if (reader["categoria"].ToString() != "")
                {
                    em.Categoria = (String)reader["categoria"];
                }
                //e.CountTilulos = (int)reader["countTitulos"];
                em.Nome_editora = (String)reader["nome_editora"];
                listBox1.Items.Add(em);
            }
            cn.Close();

            var list = listBox1.Items.Cast <Emprestimo>().OrderBy(item => item.N_emprestimo).ToList(); //Order ListBox by N_Emprestimo

            listBox1.Items.Clear();
            foreach (Emprestimo listItem in list)
            {
                listBox1.Items.Add(listItem);
            }

            ShowEmprestimo();
            ClearFields();
            CountLivrosEmFalta();
        }
        static void LerEmprestimo(List <Cliente> listaCliente, List <Livro> listaLivro, List <Emprestimo> listaEmprestimo)
        {
            // VARIAIVES
            string      cpf, numeroTombo, op;
            long        idCliente;
            bool        err;
            DateTime    dataDevolucao = DateTime.Now;
            Emprestimo  emprestimo;
            CultureInfo CultureBr = new CultureInfo(name: "pt-BR");

            // LOCALIZAÇÃO
            Console.WriteLine("\n>>>CADASTRO EMPRESTIMO<<<\n");

            do
            { // LAÇO TRATA NÚMERO TOMBO DE LIVRO
                err = false;
                Console.Write("Informe o Número Tombo do Livro: ");
                numeroTombo = Console.ReadLine();

                // SE EXISTIR LIVRO NA LISTA DE EMPRESTADO E ESTAR COM STATUS EMPRESTADO RETORNA O OBJETO
                emprestimo = EmprestimoController.NumeroTomboEmprestado(listaEmprestimo, long.Parse(numeroTombo));

                // CASO NÃO EXISTIR NÚMERO TOMBO DE LIVRO OU ELE ESTAR EMPRESTADO
                if (!LivroController.NumeroTomboExiste(listaLivro, long.Parse(numeroTombo)) || emprestimo != null)
                {
                    // CAMINHOS PARA USUARIO ESCOLHER
                    Console.WriteLine("Livro indisponível para empréstimo.\n1 - Digitar Número Tombo novamente" +
                                      "\n2 - Cadastrar Livro\n3 - Voltar ao Menu Principal ");
                    op = Console.ReadLine();

                    switch (op)                                             // SWITCH DE OPÇÕES PARA SABER QUAL CAMINHO USUARIO ESCOLHEU
                    {
                    case "2":                                               // CADASTRO CLIENTE
                        Console.Clear();                                    // LIMPA TELA
                        LerLivro(listaLivro);
                        err = true;                                         // INFORMAR O CPF NOVAMENTE POREM COM CPF JÁ CADASTRADO
                        Console.WriteLine("\n>>>CADASTRO EMPRESTIMO<<<\n"); // LOCALIZAÇÃO
                        break;

                    case "3":            // VOLTAR MENU PRINCIPAL
                        Console.Clear(); // LIMPA TELA
                        return;

                    default:     // DIGITAR CPF NOVAMENTE OU OUTRO NÚMERO/LETRA NÃO INFORMADO NO MENU
                        err = true;
                        break;
                    }
                }
            } while (err);

            do
            {
                err = false;

                // INFORMA CPF
                Console.Write("Informe o CPF do Cliente: ");
                cpf = Console.ReadLine();

                // RETORNA ID DE CLIENTE QUE TEM ESSE CPF
                idCliente = ClienteController.RetornaCLienteCpf(listaCliente, cpf);

                // CASO CPF NÃO EXISTA
                if (idCliente == -1)
                {
                    // CAMINHOS CASO CPF NÃO RECONHECIDO
                    Console.WriteLine("Cliente não cadastrado.\n1 - Digitar CPF novamente" +
                                      "\n2 - Cadastrar Cliente\n3 - Voltar ao Menu Principal ");
                    op = Console.ReadLine();

                    switch (op)                                                               // SWITCH DE OPÇÕES PARA SABER QUAL CAMINHO USUARIO ESCOLHEU
                    {
                    case "2":                                                                 // CADASTRO CLIENTE
                        Console.Clear();                                                      // LIMPA TELA
                        LerCliente(listaCliente);
                        err = true;                                                           // INFORMAR O CPF NOVAMENTE POREM COM CPF JÁ CADASTRADO
                        Console.WriteLine("\n>>>CADASTRO EMPRESTIMO<<<\n");                   // LOCALIZAÇÃO
                        Console.WriteLine("Informe o Número Tombo do Livro: " + numeroTombo); // LOCALIZAÇÃO
                        break;

                    case "3":            // VOLTAR MENU PRINCIPAL
                        Console.Clear(); // LIMPA TELA
                        return;

                    default:     // DIGITAR CPF NOVAMENTE OU OUTRO NÚMERO/LETRA NÃO INFORMADO NO MENU
                        err = true;
                        break;
                    }
                }
            } while (err);

            // ARMAZENA DATA DE DEVOLUÇÃO
            do
            {
                err = false;
                try
                {
                    Console.Write("Data de Devolução (dd/mm/yyyy): ");
                    dataDevolucao = DateTime.ParseExact(Console.ReadLine(), "d", CultureBr);
                    if ((Convert.ToDateTime(dataDevolucao)) < (Convert.ToDateTime(DateTime.Now)))
                    {
                        Console.WriteLine("Informe uma data posterior a data atual");
                        err = true;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Informe a data (dd/mm/yyyy)");
                    err = true;
                }
            } while (err);


            // ESTANCIA EMPRESTIMO ESTANCIADO
            emprestimo = new Emprestimo()
            {
                IdCliente        = idCliente,
                NumeroTombo      = long.Parse(numeroTombo),
                DataEmprestimo   = DateTime.Now,
                DataDevolucao    = dataDevolucao,
                StatusEmprestimo = 1
            };

            // ADICIONA O EMPRESTIMO NA LISTA EMPRESTIMO
            listaEmprestimo.Add(emprestimo);

            // ADICIONA LISTA NO ARQUIVO
            ArquivoController.Escrita(listaEmprestimo);

            Console.Clear(); // LIMPA TELA

            Console.WriteLine("\n>>>EMPRESTIMO CADASTRADO<<<\nPrecione qualquer tecla para continuar...");
            Console.ReadLine();

            Console.Clear();
        }