// Obtenir le prochaine numéro de transaction disponible
        private int GetNextIdTransac()
        {
            OleDbConnection connec = DatabaseManager.CreateConnection();

            int res = 1;

            try
            {
                connec.Open();
                string       requete = @"SELECT MAX(codeTransaction) 
                                   FROM [Transaction]";
                OleDbCommand cmd     = new OleDbCommand(requete, connec);
                res = (int)cmd.ExecuteScalar() + 1;
            }
            catch (InvalidCastException)
            {
                res = 1;
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
            // Return 1 si l'index n'a pas été trouvé
            return(res);
        }
        // Remplir combobox par liaison de donnée
        private void RemplirCombobox(ComboBox cbo, string nomTable, string champAffiche, string champCache)
        {
            OleDbConnection connec = DatabaseManager.CreateConnection();

            // On récupère les données de la table en paramètre
            // puis on les stocks dans une table locale "table"
            string           requete = @"SELECT *
                               FROM " + nomTable;
            OleDbCommand     cmd     = new OleDbCommand(requete, connec);
            OleDbDataAdapter da      = new OleDbDataAdapter(cmd);
            DataTable        table   = new DataTable("nomTable");

            try {
                connec.Open();

                da.Fill(table);

                // On remplit le composant par liaison de donnée
                // avec la table locale créée
                cbo.DataSource    = table;
                cbo.DisplayMember = champAffiche.ToString();
                cbo.ValueMember   = champCache.ToString();
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
        private void DeleteSelectedPoste(MetroFramework.Controls.MetroGrid controler)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // delete a whole Poste if and only if a row was selected
            DataGridViewCellCollection cells = this.GetSelectedRowData(controler);

            if (cells != null)
            {
                dbConn = DatabaseManager.GetConnection();
                dbConn.Open();
                dbTransaction = dbConn.BeginTransaction();

                try
                {
                    // delete the selected poste in cascade then commit the changes
                    int indice = (int)cells[0].Value;
                    PosteRepository.Delete(dbConn, dbTransaction, indice);
                    dbTransaction.Commit();

                    // update Dataset
                    if (controler == dgvRevenus)
                    {
                        indice = dgvRevenus.Rows.GetFirstRow(DataGridViewElementStates.Selected);
                        ds.Tables["PosteRevenus"].Rows.RemoveAt(indice);
                    }
                    else
                    {
                        indice = dgvPostesFixes.Rows.GetFirstRow(DataGridViewElementStates.Selected);
                        ds.Tables["PostesPerFixes"].Rows.RemoveAt(indice);
                    }

                    SaveTablesEnLocal();
                    // Affichage des postes à périodicité fixe
                    dgvPostesFixes.DataSource = ds.Tables["PostesPerFixes"];
                    dgvPostesFixes.ClearSelection();

                    // Affichage des postes à échéances
                    dgvPostesEcheances.DataSource = ds.Tables["PosteEcheances"];
                    dgvPostesEcheances.ClearSelection();

                    // Affichage des postes revenus
                    dgvRevenus.DataSource = ds.Tables["PosteRevenus"];
                    dgvRevenus.ClearSelection();
                }
                catch (OleDbException ex)
                {
                    dbTransaction.Rollback();
                    ErrorManager.HandleOleDBError(ex);
                }
                finally
                {
                    dbConn.Close();
                }
            }
        }
Пример #4
0
        private void ajouterType(object sender, EventArgs e)
        {
            //recuperation des valeurs des textbox
            string          type   = txtType.Text.Trim();
            OleDbConnection connec = DatabaseManager.GetConnection();

            try
            {
                // On ouvre la connexion si elle n'est pas déjà ouverte
                connec.Open();

                // vérifier si le type existe déjà
                string       requeteverif = "SELECT [libType] FROM [TypeTransaction] WHERE LCASE(libType) = @libType";
                OleDbCommand cmdVerif     = new OleDbCommand(requeteverif, connec);
                cmdVerif.Parameters.AddWithValue("@libType", type);
                OleDbDataReader drVerif = cmdVerif.ExecuteReader();

                if (!drVerif.HasRows)
                {
                    //requete SQL pour recuperer le code type le plus grand
                    string requeteMaxCodeType = "SELECT MAX(codeType) FROM [TypeTransaction]";
                    //recuperation et calcul du prochain codeType
                    OleDbCommand cmd          = new OleDbCommand(requeteMaxCodeType, connec);
                    int          nextCodeType = int.Parse(cmd.ExecuteScalar().ToString()) + 1;

                    //requete sql pour inserer le nouveau type dans la base de donnees
                    string requeteAddType = "INSERT INTO [TypeTransaction] ([codeType], [libType]) VALUES (@codeType,@libType)";
                    //insertion du nouveau dans la base de donnees
                    cmd.CommandText = requeteAddType;
                    cmd.Parameters.AddWithValue("@codeType", nextCodeType);
                    cmd.Parameters.AddWithValue("@libType", type);
                    cmd.ExecuteNonQuery();

                    MessageBox.Show(Program.settings.localize.Translate("info_type_{0}_successfully_created_msg", type),
                                    Program.settings.localize.Translate("information_caption"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show(Program.settings.localize.Translate("err_duplicate_type_msg"),
                                    Program.settings.localize.Translate("err_type_creation_caption"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtType.Text = string.Empty;
                }
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
        private void SaveTablesEnLocal()
        {
            // Création du DataSet
            ds = new DataSet();

            /////////// POSTES A ECHEANCES FIXES ///////////////////////////////////////////////
            // Créer la table qui nous intéresse pour l'affichage des Postes à périodicité fixe
            string requetePFixes = "SELECT p.codePoste as Code, p.libPoste as Description, pp.jourDuMois as [Jour du mois], pp.montant as Montant, "
                                   + "per.codePer as [Code Périodicité], per.libPer as Périodicité "
                                   + "FROM ((PostePeriodique pp "
                                   + "INNER JOIN Periodicite per ON pp.typePer = per.codePer) "
                                   + "INNER JOIN Poste p ON pp.codePoste = p.codePoste) "
                                   + "ORDER BY p.codePoste";

            OleDbCommand cmd = new OleDbCommand(requetePFixes, DatabaseManager.GetConnection());

            // Création du dataAdapter pour remplir le dataset local
            // avec les informations du SELECT
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            cmd.Connection.Open();
            try {
                // Remplissage du dataSet
                da.Fill(ds, "PostesPerFixes");

                /////////// POSTES A ECHEANCES ///////////////////////////////////////////////
                string requetePEcheances = "SELECT p.codePoste as Code, p.libPoste as Description, COUNT(e.codePoste) as Echéances, "
                                           + "SUM(e.montantEcheance) as Montant "
                                           + "FROM ((Poste p "
                                           + "INNER JOIN PostePonctuel pp ON p.codePoste = pp.codePoste) "
                                           + "INNER JOIN Echeances e ON e.codePoste = pp.codePoste)"
                                           + "GROUP BY p.codePoste, p.libPoste "
                                           + "ORDER BY p.codePoste";
                cmd.CommandText = requetePEcheances;
                da.Fill(ds, "PosteEcheances");

                /////////// POSTES REVENUS ///////////////////////////////////////////////
                string requetePRevenus = "SELECT p.codePoste as Code, p.libPoste as Description, pr.jourDuMois as [Jour du mois], "
                                         + "pers.codePersonne as [Code Bénéficiaire], "
                                         + "pers.nomPersonne+\" \"+pers.pnPersonne as Bénéficiaire, pr.montant "
                                         + "FROM ((Poste p "
                                         + "INNER JOIN PosteRevenu pr ON p.codePoste = pr.codePoste) "
                                         + "INNER JOIN Personne pers ON pers.codePersonne = pr.codePersonne) "
                                         + "ORDER BY p.codePoste";
                cmd.CommandText = requetePRevenus;
                da.Fill(ds, "PosteRevenus");
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
Пример #6
0
        private void FillBeneficiaireList()
        {
            this.listBeneficiairesComboBox.Items.Clear();

            try {
                this.listBeneficiairesComboBox.Items.AddRange(PersonneRepository.List());
            } catch (OleDbException e)
            {
                ErrorManager.HandleOleDBError(e);
            }
        }
        private void modifierPosteFixeToolStripItem_Click(object sender, EventArgs e)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // delete a whole Poste if and only if a row was selected
            DataGridViewCellCollection cells = this.GetSelectedRowData(dgvPostesFixes);

            if (cells != null)
            {
                ModifierEntreePosteFixe formEntry =
                    new ModifierEntreePosteFixe(new PostePeriodiqueRepository.PostePeriodiqueModel()
                {
                    codePoste  = (int)cells[0].Value,
                    libPoste_s = cells[1].Value.ToString(),
                    jourDuMois = (int)cells[2].Value,
                    montant    = decimal.Parse(cells[3].Value.ToString()),
                    typePer    = (int)cells[4].Value
                }
                                                );

                if (formEntry.ShowDialog() == DialogResult.OK)
                {
                    dbConn = DatabaseManager.GetConnection();
                    dbConn.Open();

                    dbTransaction = dbConn.BeginTransaction();

                    try
                    {
                        PostePeriodiqueRepository.Update(dbConn, dbTransaction,
                                                         formEntry.originalData, formEntry.editedData);
                        dbTransaction.Commit();
                        //update dgv
                        int rowToModify = dgvPostesFixes.Rows.GetFirstRow(DataGridViewElementStates.Selected);
                        dgvPostesFixes.Rows[rowToModify].SetValues(formEntry.originalData.codePoste,
                                                                   formEntry.editedData.libPoste_s,
                                                                   formEntry.editedData.jourDuMois,
                                                                   formEntry.editedData.montant,
                                                                   formEntry.editedData.typePer,
                                                                   formEntry.editedData.libPer_s);
                    }
                    catch (OleDbException ex)
                    {
                        ErrorManager.HandleOleDBError(ex);
                    }
                    finally
                    {
                        dbConn.Close();
                    }
                }
            }
        }
Пример #8
0
        private void FillPostes()
        {
            listBoxPostes.Items.Clear();
            listBoxPostes.ClearSelected();

            try {
                listBoxPostes.Items.AddRange(
                    PosteRepository.List()
                    );
            } catch (OleDbException e)
            {
                ErrorManager.HandleOleDBError(e);
            }
        }
Пример #9
0
        private void FillPeriodicitesComboBox()
        {
            // empty the ComboBox
            this.ComboxBoxListePeriodicites.Items.Clear();

            try {
                // Translate and add every item
                foreach (PeriodiciteRepository.PeriodiciteModel e in
                         PeriodiciteRepository.List())
                {
                    e.libPer = Program.settings.localize.Translate(e.libPer);
                    this.ComboxBoxListePeriodicites.Items.Add(e);
                }
            } catch (OleDbException e)
            {
                ErrorManager.HandleOleDBError(e);
            }
        }
Пример #10
0
        private void FillPostesComboBox()
        {
            // empty the ComboBox
            this.ComboxBoxListePostes.Items.Clear();

            // Reset the selection
            this.ComboxBoxListePostes.ResetText();
            this.ComboxBoxListePostes.Refresh();

            try
            {
                this.ComboxBoxListePostes.Items.AddRange(PosteRepository.ListAvailableToUse());
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
        }
Пример #11
0
        static void RunApp()
        {
            FrmMain      MainForm;
            UserCreation CreationForm;

            try {
                // run the Main form and restart it if it asks so
                do
                {
                    // load settings from saved data if available. Otherwise: create settings
                    Program.settings = Settings.Load();
                    if (Program.settings == null)
                    {
                        Program.settings = new Settings();
                    }

                    // If there is nobody in the database, open the creation form
                    while (PersonneRepository.CountRows() == 0)
                    {
                        // !!TODO!!
                        CreationForm = new UserCreation();
                        Application.Run(CreationForm);

                        // Stop user cancelled the user creation, close the program
                        if (CreationForm.UserCancelled)
                        {
                            return;
                        }
                    }

                    MainForm = new FrmMain();
                    Application.Run(MainForm);
                } while (MainForm.WaitsForRestart);
            }
            // handle any fatal OleDB error
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            catch (Exception ex)
            {
                ErrorManager.HandleBaseException(ex);
            }
        }
        ////////////// FONCTIONS OUTILS ///////////////////////////////////////////////////////////////////
        // Remplir listbox par liaison de donnée
        private void RemplirListboxNomPrenom()
        {
            OleDbConnection connec = DatabaseManager.CreateConnection();

            // On récupère les données de la table Personne
            // puis on les stocks dans une table locale "Personne"
            string           requete     = @"SELECT *
                               FROM [Personne]";
            OleDbCommand     cmd         = new OleDbCommand(requete, connec);
            OleDbDataAdapter da          = new OleDbDataAdapter(cmd);
            DataTable        tblPersonne = new DataTable("Personne");

            try
            {
                connec.Open();

                da.Fill(tblPersonne);

                // On créé une colonne NOM+PRENOM pour pouvoir  faire la liaison de donnée
                tblPersonne.Columns.Add("NomPrenom");
                foreach (DataRow dr in tblPersonne.Rows)
                {
                    dr["NomPrenom"] = dr["nomPersonne"] + " " + dr["pnPersonne"];
                }

                // On complète la listbox avec les "Noms Prénoms" des personnes
                // par liaison de donnée
                // avec la table locale créée
                listBoxAjoutTransaction_Personne.DataSource    = tblPersonne;
                listBoxAjoutTransaction_Personne.DisplayMember = "NomPrenom";
                listBoxAjoutTransaction_Personne.ValueMember   = "codePersonne";

                // On désélectionne tous les éléments
                listBoxAjoutTransaction_Personne.ClearSelected();
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
Пример #13
0
        private void AcceptButton_Click(object sender, EventArgs e)
        {
            //recuperation des valeurs des textbox
            string nom    = txtNom.Text;
            string prenom = txtPrenom.Text;
            string tel    = txtTel.Text.Replace(" ", "");

            OleDbConnection connec = DatabaseManager.GetConnection();

            //requete SQL pour recuperer le code personne le plus grand
            string sqlCodePersonne = "SELECT MAX(codePersonne) FROM Personne";
            //requete sql pour inserer la nouvelle personne dans la base de donnees
            string sqlAjoutPersonne = "INSERT INTO Personne ([codePersonne], [nomPersonne], [pnPersonne], [telMobile]) VALUES (?,?,?,?)";

            //recuperation et calcul du prochain codePersonne
            OleDbCommand cmd = new OleDbCommand(sqlCodePersonne, connec);

            try
            {
                connec.Open();
                int codePersonne = int.Parse(cmd.ExecuteScalar().ToString()) + 1;

                //insertion de la personne dans la base de donnees
                cmd.CommandText = sqlAjoutPersonne;
                cmd.Parameters.AddWithValue("@codePersonne", codePersonne);
                cmd.Parameters.AddWithValue("@nomPersonne", nom);
                cmd.Parameters.AddWithValue("@pnPersonne", prenom);
                cmd.Parameters.AddWithValue("@telMobile", string.IsNullOrEmpty(tel) ? (object)DBNull.Value : tel); //si jamais le telephone n'est pas renseigne, on insert null dans la colonne telMobile
                cmd.ExecuteNonQuery();

                ErrorManager.EntriesSuccessfullyAdded(this);
                this.DialogResult = DialogResult.OK;
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                this.Close();
            }
        }
        ////////////// Postes à échéances //////////////////////////////////////////////////
        // Double clique gauche sur les Postes à échéances permet d'afficher des détails sur ce poste
        private void dgvPostesEcheances_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0 && dgvPostesEcheances.SelectedCells != null)
            {
                DataGridViewCellCollection selectedRowCells = GetSelectedRowData(dgvPostesEcheances);
                int    codePoste  = (int)selectedRowCells[0].Value;
                string descrPoste = selectedRowCells[1].Value.ToString();

                string requeteDetailPostes = "SELECT datePrelevt, montantEcheance "
                                             + "FROM Echeances "
                                             + "WHERE codePoste = @codePoste";

                OleDbCommand cmd = new OleDbCommand(requeteDetailPostes, DatabaseManager.GetConnection());
                cmd.Parameters.AddWithValue("@codePoste", codePoste);
                cmd.Connection.Open();

                try
                {
                    OleDbDataReader dr = cmd.ExecuteReader();

                    string detailsEcheance = string.Empty;
                    while (dr.Read())
                    {
                        detailsEcheance += "Date prévue : " + dr[0].ToString().Substring(0, 10) + " Montant : " + dr[1] + "\n";
                    }

                    // Affichage des détails
                    FrmAffichDetailsPoste frmADP = new FrmAffichDetailsPoste(codePoste, descrPoste, detailsEcheance);
                    frmADP.ShowDialog();
                }
                catch (OleDbException o)
                {
                    ErrorManager.HandleOleDBError(o);
                }
                finally
                {
                    cmd.Connection.Close();
                }
            }
        }
Пример #15
0
        private void DeleteEntries(object s, object e)
        {
            // if the form is waiting for a commit/ rollback from the user:
            // do nothing.
            if (this.RequiresCommitAndShowError())
            {
                return;
            }

            OleDbCommand rmCmd;

            PosteRepository.PosteModel entry;
            int          removePos;
            DialogResult?dialogResult = null;

            // start the transaction mode
            this.BeginTransaction();

            // will there are data to remove and there is no error
            while (this.listBoxPostes.SelectedIndices.Count > 0 && dialogResult == null)
            {
                removePos = this.listBoxPostes.SelectedIndices[0];
                entry     = (PosteRepository.PosteModel) this.listBoxPostes.Items[removePos];

                try
                {
                    // Delete in cascade the given poste
                    PosteRepository.Delete(dbConn, transaction, entry.codePoste);

                    // then remove it from the list
                    this.listBoxPostes.Items.RemoveAt(removePos);
                }
                catch (OleDbException exc)
                {
                    this.RollbackTransaction();
                    ErrorManager.HandleOleDBError(exc);
                }
            }
        }
Пример #16
0
        ///////////////// FONCTIONS /////////////////////////////////////////
        private void SaveTableEnLocal(string nomTable)
        {
            OleDbConnection connec = DatabaseManager.GetConnection();

            // Création du DataSet
            ds = new DataSet();

            // Création de la commande SELECT toutes les transactions
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + nomTable + "]", connec);

            // Création du dataAdapter pour remplir le dataset local
            // avec les informations du SELECT
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            // Vérifier si la table existe, si oui, la supprimer
            if (ds.Tables.Contains(nomTable))
            {
                ds.Tables.Remove(nomTable);
            }

            // Ouverture de la connexion
            connec.Open();

            try
            {
                // Remplissage du dataSet
                da.Fill(ds, nomTable);
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
Пример #17
0
        private void supprimerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Création d'une transaction de suppréssion de la "transaction"
            OleDbTransaction transac = null;
            OleDbConnection  connec;

            // On récupère l'index de la ligne sélectionnée
            int rowToDelete = dgvTransac.Rows.GetFirstRow(DataGridViewElementStates.Selected);
            int idTransac   = (int)dgvTransac.Rows[rowToDelete].Cells[0].Value;
            // On propose de la supprimer
            DialogResult sure = MessageBox.Show(
                Program.settings.localize.Translate("delete_confirmation_msg"),
                "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Warning
                );

            if (sure == DialogResult.Yes)
            {
                // Ouverture de la connection
                connec = DatabaseManager.GetConnection();
                connec.Open();

                // Début de la transaction
                transac = connec.BeginTransaction();

                // On supprime tous les bénéficiaires de la transaction à supprimer
                string requetedelBenef = "DELETE "
                                         + "FROM [Beneficiaires] "
                                         + "WHERE [codeTransaction] = @idTransac";
                OleDbCommand cmdDelBenef = new OleDbCommand(requetedelBenef, connec);
                cmdDelBenef.Parameters.AddWithValue("@idTransac", idTransac);
                cmdDelBenef.Transaction = transac;

                try {
                    cmdDelBenef.ExecuteNonQuery();

                    // Construction de la requete DELETE de la transaction en elle-meme
                    string requeteDelTransac = "DELETE "
                                               + "FROM [Transaction] "
                                               + "WHERE [codeTransaction] = @idTransac";
                    OleDbCommand cmdDelTransac = new OleDbCommand(requeteDelTransac, connec);
                    cmdDelTransac.Parameters.AddWithValue("@idTransac", idTransac);
                    cmdDelTransac.Transaction = transac;
                    cmdDelTransac.ExecuteNonQuery();

                    // On valide la transaction si il n'y a aucun soucis
                    transac.Commit();
                }
                catch (OleDbException ex)
                {
                    ErrorManager.HandleOleDBError(ex);
                }
                finally
                {
                    connec.Close();
                }

                // Metre à jour le dataset local
                SaveTableEnLocal("Transaction");
                dgvTransac.DataSource = ds.Tables["Transaction"];
                // Nettoyer la zone de recherche
                btnClear_Click(null, null);

                MessageBox.Show(Program.settings.localize.Translate("transactions_successfully_removed_msg"),
                                Program.settings.localize.Translate("msg_entries_successfully_added_msg"),
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            // Tout déselectionner dans le dgv
            dgvTransac.ClearSelection();
        }
Пример #18
0
        private void BtnValiderBudgetFixe_Click(object _s, EventArgs e)
        {
            MetroButton sender = (MetroButton)_s;

            PosteRepository.PosteModel             SelectedPoste;
            PeriodiciteRepository.PeriodiciteModel SelectedPeriode;
            decimal montant;
            int     TousLesXDuMois;

            // disable submit button
            sender.Enabled = false;

            // Check if every field was filled
            if (
                this.ComboxBoxListePeriodicites.SelectedItem == null ||
                this.ComboxBoxListePostes.SelectedItem == null ||
                this.TxtBoxTousLesXMois.Text.Length < 1 ||
                this.TxtBoxMontantPosteFixe.Text.Length < 1
                )
            {
                MetroMessageBox.Show(this,
                                     Program.settings.localize.Translate("err_missing_fields_msg"),
                                     Program.settings.localize.Translate("err_missing_fields_caption"),
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // try to convert the decimals and integers
            else if (!(LocalizationManager.ConvertFloatingTo <decimal>(TxtBoxMontantPosteFixe.Text, decimal.TryParse, out montant) &&
                       int.TryParse(TxtBoxTousLesXMois.Text, out TousLesXDuMois)))
            {
                MetroMessageBox.Show(this,
                                     Program.settings.localize.Translate("err_day_of_month_and_sum_not_number"),
                                     Program.settings.localize.Translate("err_uh_oh_caption"),
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // retrieve the selected items
                SelectedPoste   = (PosteRepository.PosteModel) this.ComboxBoxListePostes.SelectedItem;
                SelectedPeriode = (PeriodiciteRepository.PeriodiciteModel) this.ComboxBoxListePeriodicites.SelectedItem;

                OleDbCommand cmd = DatabaseManager.InsertInto("PostePeriodique",
                                                              DatabaseManager.GetConnection(),
                                                              new KeyValuePair <string, object>("codePoste", SelectedPoste.codePoste),
                                                              new KeyValuePair <string, object>("typePer", SelectedPeriode.codePer),
                                                              new KeyValuePair <string, object>("montant", montant),
                                                              new KeyValuePair <string, object>("jourDuMois", TousLesXDuMois)
                                                              );

                try
                {
                    if (PosteRepository.IsAvailable(SelectedPoste.codePoste))
                    {
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();  // insert data

                        ErrorManager.EntriesSuccessfullyAdded(this);
                        ClearPosteFixeForm();
                    }
                    else
                    {
                        ErrorManager.ShowAlreadyUsedError(this, this.lblCmbPostes.Text);
                    }
                }
                catch (OleDbException ex)
                {
                    ErrorManager.HandleOleDBError(ex);
                }
                finally
                {
                    cmd.Connection.Close();
                }

                this.FillPostesComboBox();
            }

            // re-enable the submit button
            sender.Enabled = true;
        }
Пример #19
0
        private void FrmCalendrierPrev_Load(object sender, EventArgs e)
        {
            //tableau des mois et des noms de colonnes
            string[] mois   = { "Poste", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" };
            string[] titres = { "Poste", "Janvier", "Fevrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre" };
            for (int i = 0; i < 13; i++)
            {
                //nom de colonne = col<mois>
                dgvCalendrier.Columns.Add(string.Format("col{0}", titres[i]), mois[i]);
            }

            //on gèle la première colonne des postes
            this.dgvCalendrier.Columns["colPoste"].Frozen = true;

            ds = new DataSet();

            //tables à importer
            string[] tables =
            {
                "Poste",
                "PostePeriodique",
                "PostePonctuel",
                "PosteRevenu",
                "Echeances",
                "Periodicite"
            };

            OleDbCommand cmd = new OleDbCommand();

            cmd.Connection = DatabaseManager.GetConnection();
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

            cmd.Connection.Open();

            try
            {
                //import des tables en local
                foreach (string table in tables)
                {
                    cmd.CommandText = "SELECT * FROM [" + table + "]";
                    adapter.Fill(ds, table);
                }


                //définition des clés primaires sur les tables
                DataColumn PPeriodPK      = ds.Tables["PostePeriodique"].Columns["codePoste"];
                DataColumn PPonctPK       = ds.Tables["PostePonctuel"].Columns["codePoste"];
                DataColumn PRevenuPK      = ds.Tables["PosteRevenu"].Columns["codePoste"];
                DataColumn PPeriodicitePK = ds.Tables["Periodicite"].Columns["codePer"];

                //applications des clés primaires
                ds.Tables["PostePeriodique"].PrimaryKey = new DataColumn[] { PPeriodPK };
                ds.Tables["PostePonctuel"].PrimaryKey   = new DataColumn[] { PPonctPK };
                ds.Tables["PosteRevenu"].PrimaryKey     = new DataColumn[] { PRevenuPK };
                ds.Tables["Periodicite"].PrimaryKey     = new DataColumn[] { PPeriodicitePK };

                //remplissage de la première colonne
                for (int i = 0; i < ds.Tables["Poste"].Rows.Count; i++)
                {
                    dgvCalendrier.Rows.Add();
                    DataRow d = ds.Tables["Poste"].Rows[i];
                    dgvCalendrier.Rows[i].Cells["colPoste"].Value = d["libPoste"];
                    dgvCalendrier.Rows[i].Cells["colPoste"].Tag   = d["codePoste"];
                }

                //on boucle sur chacun des postes
                for (int i = 0; i < dgvCalendrier.RowCount; i++)
                {
                    //switch sur le type du poste
                    switch (getTypePoste(dgvCalendrier.Rows[i].Cells["colPoste"]))
                    {
                    //remplissage du datagridview pour un poste Revenu
                    case ("PosteRevenu"):
                        DataRow r = ds.Tables["PosteRevenu"].Rows.Find(dgvCalendrier.Rows[i].Cells["colPoste"].Tag);
                        for (int j = 1; j < 13; j++)
                        {
                            dgvCalendrier.Rows[i].Cells[j].Value = r["montant"];
                        }
                        break;

                    //remplissage du datagridview pour un poste Ponctuel
                    case ("PostePonctuel"):
                        //on regarde quels mois sont des mois où l'on doit rembourser
                        DataRow[] r2 = ds.Tables["Echeances"].Select("codePoste = " + dgvCalendrier.Rows[i].Cells["colPoste"].Tag);

                        int[] moisRemboursement = new int[r2.Length];     //tableau contenant les mois de remboursement

                        //remplissage de moisRemboursement
                        for (int j = 0; j < r2.Length; j++)
                        {
                            DateTime dt = (DateTime)r2[j]["datePrelevt"];
                            moisRemboursement[j] = dt.Month;
                        }


                        //on remplit le datagrisview avec les valeurs attendues
                        for (int j = 1; j < 13; j++)
                        {
                            //si le mois est un mois où l'on doit rembourser
                            if (Array.IndexOf(moisRemboursement, j) != -1)
                            {
                                dgvCalendrier.Rows[i].Cells[j].Value = r2[0]["montantEcheance"];
                            }
                            else
                            {
                                dgvCalendrier.Rows[i].Cells[j].Value = 0;
                            }
                        }
                        break;

                    //remplissage du datagridview pour un poste Periodique
                    case ("PostePeriodique"):
                        DataRow r3 = ds.Tables["PostePeriodique"].Rows.Find((dgvCalendrier.Rows[i].Cells["colPoste"].Tag));

                        //on récupère la périodicié de
                        string periodicite = ds.Tables["Periodicite"].Rows.Find(r3["typePer"]).ItemArray[1].ToString();
                        for (int j = 1; j < 13; j++)
                        {
                            //on regarde quel est la périodicité du poste périodique
                            switch (periodicite)
                            {
                            case ("hebdomadaire"):
                                //calcul du nombre de semaines dans le mois
                                int jours    = DateTime.DaysInMonth(DateTime.Now.Year, j);
                                int semaines = (int)Math.Ceiling((jours) / 7.0);

                                //remplissage du dataGridView
                                dgvCalendrier.Rows[i].Cells[j].Value = float.Parse(r3["montant"].ToString()) * semaines;
                                break;

                            case ("mensuel"):
                                dgvCalendrier.Rows[i].Cells[j].Value = r3["montant"].ToString();
                                break;

                            case ("bimestriel"):
                                if ((j - 1) % 2 == 0)
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = r3["montant"].ToString();
                                }
                                else
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = 0;
                                }
                                break;

                            case ("trimestriel"):
                                if ((j - 1) % 3 == 0)
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = r3["montant"].ToString();
                                }
                                else
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = 0;
                                }
                                break;

                            case ("semestriel"):
                                if ((j - 1) % 6 == 0)
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = r3["montant"].ToString();
                                }
                                else
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = 0;
                                }
                                break;

                            case ("annuel"):
                                if ((j - 1) == 0)
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = r3["montant"].ToString();
                                }
                                else
                                {
                                    dgvCalendrier.Rows[i].Cells[j].Value = 0;
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (OleDbException ex)
            {
                // if error: handle and abort everything
                ErrorManager.HandleOleDBError(ex);
                this.Close();
                return;
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
Пример #20
0
        private void btnValiderRevenu_Click(object _s, EventArgs _ev)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // Retrieve the budget's title + comments and remove any leading whitespacess
            string  revenuPoste = this.txtBoxPosteRevenu.Text.Trim();
            decimal revenuMontant;
            int     chaqueXDuMois;

            PersonneRepository.PersonneModel personne;

            // try to convert the user amount to a decimal and the day to a int,
            // if it fails, we trigger a "not a number" error and we stop proceeding
            if (!LocalizationManager.ConvertFloatingTo <decimal>(this.txtBoxMontantRevenu.Text, decimal.TryParse, out revenuMontant) ||
                !this.isDayOfTheMonth(this.txtTousLesXDuMoisRevenu.Text, out chaqueXDuMois))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // - if:
            //     - the poste is null/empty
            //     - or only has spaces:
            //     - or the beneficiary is not selected
            //   ---> show missing fields error and stop proceeding
            //
            // - otherwise: proceed and insert the data (if the poste does not exist yet)
            if (this.listBeneficiairesComboBox.SelectedItem == null ||
                string.IsNullOrWhiteSpace(revenuPoste))
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }

            // retrieve the selected beneficiary
            personne = (PersonneRepository.PersonneModel)listBeneficiairesComboBox.SelectedItem;

            // check if the budgetTitle is unique in the database
            // if not unique: show an error saying that it already exists and stop proceeding
            try {
                if (!PosteRepository.IsUnique(revenuPoste))
                {
                    // show a duplicate value error and specify the field
                    ErrorManager.ShowDuplicateError(this,
                                                    Program.settings.localize.Translate(this.lblPosteRevenu.Name));
                    return;
                }
            } catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
                return;
            }

            // otherwise: continue and insert the data
            dbConn = DatabaseManager.GetConnection();

            dbConn.Open();

            dbTransaction = dbConn.BeginTransaction();

            // Insert the data to the data base
            try
            {
                PosteRevenuRepository.Create(dbConn, dbTransaction,
                                             revenuPoste,
                                             personne,
                                             revenuMontant,
                                             chaqueXDuMois
                                             );

                Console.WriteLine("<- Commit");
                dbTransaction.Commit();

                ErrorManager.EntriesSuccessfullyAdded(this);
                ClearPosteRevenuForm();
            }
            catch (OleDbException e)
            {
                // cancel the changes
                dbTransaction.Rollback();

                // handle the error (log it and report it to the user)
                ErrorManager.HandleOleDBError(e);
            }
            catch (ArgumentException e)
            {
                ErrorManager.ShowOperationFailed(this, Program.settings.localize.Translate(e.Message));
            }
            finally
            {
                dbConn.Close();
            }
        }
        // Valider la transaction
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Récupération des informations du formulaire
            string dateTransaction = calAjoutTransaction.Value.ToShortDateString();
            string description     = txtAjoutTransaction_desc.Text;
            double montant;
            int    type      = (int)cboAjoutTransaction_Type.SelectedValue;
            int    idTransac = GetNextIdTransac(); // Récupérer le numéro de la prochaine transaction

            int codeRetour;

            // Tente de convertir le montant en un double. Sinon : affiche une erreur et stop le traitement.
            if (!LocalizationManager.ConvertFloatingTo <double>(txtAjoutTransaction_montant.Text, double.TryParse, out montant))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // Ouverture de la connection
            OleDbConnection connec = DatabaseManager.CreateConnection();

            // Construction de la chaine de la requête
            string requeteTransac = @"INSERT INTO [Transaction]
                                        VALUES (?,?,?,?,?,?,?)";

            // Création de la requete INSERT de la transaction
            OleDbCommand cmdTransac = new OleDbCommand(requeteTransac, connec);

            cmdTransac.Parameters.AddWithValue("@codeTransaction", idTransac);
            cmdTransac.Parameters.AddWithValue("@dateTransaction", dateTransaction);

            // Si jamais la description n'est pas renseigne, on insert "NULL" dans la colonne description
            cmdTransac.Parameters.AddWithValue("@description", string.IsNullOrEmpty(description) ? (object)DBNull.Value : description);
            cmdTransac.Parameters.AddWithValue("@montant", montant > 0 ? montant : montant * -1);
            cmdTransac.Parameters.AddWithValue("@recetteON", ckbAjoutTransaction_recette.Checked);
            cmdTransac.Parameters.AddWithValue("@percuON", ckbAjoutTransaction_percu.Checked);
            cmdTransac.Parameters.AddWithValue("@type", type);

            try {
                // Execution de la requête
                connec.Open();
                codeRetour = cmdTransac.ExecuteNonQuery();

                // Création des requetes dans la table des bénéficiaires
                OleDbCommand cmdBenef = new OleDbCommand();
                cmdBenef.Connection = connec;
                string requeteBenef = @"INSERT INTO [Beneficiaires]([codeTransaction], [codePersonne])
                                            VALUES (?,?)";
                cmdBenef.CommandText = requeteBenef;
                string numPers = string.Empty;

                // Pour chaque personne sélectionnée dans la listbox,
                // ajouter la transaction avec le codePersonne correspondant
                foreach (DataRowView drw in listBoxAjoutTransaction_Personne.SelectedItems)
                {
                    cmdBenef.Parameters.Clear();
                    numPers = drw.Row[0].ToString();
                    cmdBenef.Parameters.AddWithValue("@codeTransaction", idTransac);
                    cmdBenef.Parameters.AddWithValue("@codePersonne", numPers);
                    cmdBenef.ExecuteNonQuery();
                }
                ///////// Envoi d'un SMS si la somme dépasse la totalité des revenus + 10 %
                // Recherche et calcul du revenu de la famille
                string       requeteSumRevenus = "SELECT SUM(montant) FROM [PosteRevenu]";
                OleDbCommand cmdSumRevenus     = new OleDbCommand(requeteSumRevenus, connec);

                double sumRevenus  = (double)cmdSumRevenus.ExecuteScalar();
                double sommeLimite = sumRevenus + 0.1 * sumRevenus;
                //MessageBox.Show("Revenu : " + sumRevenus + "\n" + "Somme limite : " + sommeLimite);
                List <string> numerosTel = new List <string>();

                // Si le montant de la transaction dépasse cette somme max, alors on envoi
                // un sms a tous les numéros renseignés dans la base
                if (montant > sommeLimite)
                {
                    // On récupère tous les numéros de téléphone de la table Personne
                    string          requeteAllNum = "SELECT telMobile FROM [Personne] WHERE telMobile IS NOT NULL";
                    OleDbCommand    cmdAllNum     = new OleDbCommand(requeteAllNum, connec);
                    OleDbDataReader drAllNum      = cmdAllNum.ExecuteReader();
                    while (drAllNum.Read())
                    {
                        string num = drAllNum[0].ToString();
                        if (num[0] == '0')
                        {
                            num = num.Substring(1, num.Length - 1);
                            num = "+33" + num;
                        }
                        //MessageBox.Show("Numéro : " + num);
                        numerosTel.Add(num);
                    }
                }

                // Envoi des SMS
                string message = "Message automatique de BreakingBudget\n" +
                                 "ATTENTION : Quelqu'un a saisi une transaction d'un montant anormalement élevé de " + montant;
                SMSManager.SendSMS(this, numerosTel.ToArray(), message);

                // Show message success
                ErrorManager.EntriesSuccessfullyAdded(this);

                // Clear formulaire
                btnClear_Click(null, null);
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }

            // TODO: SMS API
        }
Пример #22
0
        private void AddEntry(object s, object e)
        {
            // if the form is waiting for a commit/ rollback from the user:
            // do nothing.
            if (this.RequiresCommitAndShowError())
            {
                return;
            }

            InputMessageBox inputBox = new InputMessageBox("Add", null, null);

            inputBox.ShowDialog();

            // if the user didn't cancel
            if (!inputBox.userCancelled)
            {
                if (string.IsNullOrWhiteSpace(inputBox.userInput))
                {
                    MetroMessageBox.Show(this,
                                         Program.settings.localize.Translate("err_invalid_input_empty"),
                                         Program.settings.localize.Translate("err_invalid_input_caption"),
                                         MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!IsUnique(inputBox.userInput))
                {
                    MetroMessageBox.Show(this,
                                         Program.settings.localize.Translate("err_duplicate_value"),
                                         Program.settings.localize.Translate("err_duplicate_value_caption"),
                                         MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // create a new Poste model,
                // add the user's input to it
                PosteRepository.PosteModel newPoste = new PosteRepository.PosteModel();

                // we retrieve the biggest existing Poste identifier currently in the
                // database and we increment it.
                newPoste.codePoste = PosteRepository.BiggestID() + 1;
                newPoste.libPoste  = inputBox.userInput;

                // append the newly created Poste to the list and to the queue

                //this.BeginTransaction();
                this.dbConn.Open();
                OleDbCommand cmd = new OleDbCommand(
                    "INSERT INTO Poste (codePoste, libPoste) VALUES(@codePoste, @libPoste)", this.dbConn);
                cmd.Parameters.AddWithValue("@codePoste", newPoste.codePoste);
                cmd.Parameters.AddWithValue("@libPoste", newPoste.libPoste);

                try
                {
                    cmd.ExecuteNonQuery();
                    this.listBoxPostes.Items.Add(newPoste);
                }
                catch (OleDbException exc)
                {
                    ErrorManager.HandleOleDBError(exc);
                }
                finally
                {
                    this.dbConn.Close();
                }
            }
        }
Пример #23
0
        // Valider la transaction
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Récupération des informations du formulaire
            string  dateTransaction = calAjoutTransaction.Value.ToShortDateString();
            string  description     = txtDesc.Text;
            decimal montant;
            int     type      = (int)cboType.SelectedValue;
            int     idTransac = GetNextIdTransac(); // Récupérer le numéro de la prochaine transaction

            int codeRetour;

            // Tente de convertir le montant en un double. Sinon : affiche une erreur et stop le traitement.
            if (!LocalizationManager.ConvertFloatingTo <decimal>(txtMontant.Text, decimal.TryParse, out montant))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // Ouverture de la connection
            OleDbConnection connec = DatabaseManager.GetConnection();

            // Construction de la chaine de la requête
            string requeteTransac = @"INSERT INTO [Transaction]
                                        VALUES (?,?,?,?,?,?,?)";

            // Création de la requete INSERT de la transaction
            OleDbCommand cmdTransac = new OleDbCommand(requeteTransac, connec);

            cmdTransac.Parameters.AddWithValue("@codeTransaction", idTransac);
            cmdTransac.Parameters.AddWithValue("@dateTransaction", dateTransaction);

            // Si jamais la description n'est pas renseigne, on insert "NULL" dans la colonne description
            cmdTransac.Parameters.AddWithValue("@description", string.IsNullOrEmpty(description) ? (object)DBNull.Value : description);
            cmdTransac.Parameters.AddWithValue("@montant", montant);
            cmdTransac.Parameters.AddWithValue("@recetteON", ckbRecette.Checked);
            cmdTransac.Parameters.AddWithValue("@percuON", ckbPercu.Checked);
            cmdTransac.Parameters.AddWithValue("@type", type);

            try
            {
                // Execution de la requête
                connec.Open();
                codeRetour = cmdTransac.ExecuteNonQuery();

                // Création des requetes dans la table des bénéficiaires
                OleDbCommand cmdBenef = new OleDbCommand();
                cmdBenef.Connection = connec;
                string requeteBenef = @"INSERT INTO [Beneficiaires]([codeTransaction], [codePersonne])
                                            VALUES (?,?)";
                cmdBenef.CommandText = requeteBenef;
                string numPers = string.Empty;

                // Pour chaque personne sélectionnée dans la listbox,
                // ajouter la transaction avec le codePersonne correspondant
                foreach (DataRowView drw in listBoxAjoutTransaction_Personne.SelectedItems)
                {
                    cmdBenef.Parameters.Clear();
                    numPers = drw.Row[0].ToString();
                    cmdBenef.Parameters.AddWithValue("@codeTransaction", idTransac);
                    cmdBenef.Parameters.AddWithValue("@codePersonne", numPers);
                    cmdBenef.ExecuteNonQuery();
                }
                ErrorManager.EntriesSuccessfullyAdded(this);


                // if the amount is a expense
                if (montant < 0)
                {
                    ///////// Envoi d'un SMS si la somme dépasse la totalité des revenus + 10 %
                    // Recherche et calcul du revenu de la famille
                    string       requeteSumRevenus = "SELECT SUM(montant) FROM [PosteRevenu]";
                    OleDbCommand cmdSumRevenus     = new OleDbCommand(requeteSumRevenus, connec);

                    object _sumRevenus = cmdSumRevenus.ExecuteScalar();

                    // we put in decimal because of a bug from the VS compiler installed in rds's server
                    // (see https://github.com/dotnet/roslyn/issues/7148)
                    decimal sumRevenus = (_sumRevenus.GetType() != typeof(DBNull)) ? decimal.Parse(_sumRevenus.ToString()) : 0;

                    // put the sum Revenu to negative to compare the negative expense
                    decimal sommeLimite = (sumRevenus * -1) - 0.1M * sumRevenus;

                    List <string> numerosTel = new List <string>();

                    // Si le montant de la transaction dépasse cette somme max, alors on envoi
                    // un sms a tous les numéros renseignés dans la base
                    if (montant < sommeLimite)
                    {
                        // On récupère tous les numéros de téléphone de la table Personne
                        string          requeteAllNum = "SELECT telMobile FROM [Personne] WHERE telMobile IS NOT NULL";
                        OleDbCommand    cmdAllNum     = new OleDbCommand(requeteAllNum, connec);
                        OleDbDataReader drAllNum      = cmdAllNum.ExecuteReader();
                        while (drAllNum.Read())
                        {
                            string num = drAllNum[0].ToString();
                            if (num[0] == '0')
                            {
                                num = num.Substring(1, num.Length - 1);
                                num = "+33" + num;
                            }
                            numerosTel.Add(num);
                        }

                        // if there are num found
                        if (numerosTel.Count > 0)
                        {
                            // Envoi des SMS
                            string message = string.Format(Program.settings.localize.Translate("sms_big_expense_msg_{0}"), montant);
                            SMSManager.SendSMS(this, numerosTel.ToArray(), message);
                            ErrorManager.SMSSuccessfullySent(this);
                        }
                    }
                }

                // Clear formulaire
                btnClearAjoutTransaction_Click(null, null);

                this.Close();
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
Пример #24
0
        private void FrmAffichage1par1_Load(object sender, EventArgs e)
        {
            OleDbConnection connec = DatabaseManager.GetConnection();

            //différentes tables à télécharger en local
            string[] listeTables =
            {
                "Personne",
                "Beneficiaires",
            };

            OleDbCommand cmd = new OleDbCommand();

            cmd.Connection = connec;
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

            try
            {
                connec.Open();

                //récupération des tables en local
                foreach (string elt in listeTables)
                {
                    cmd.CommandText = "SELECT * FROM [" + elt + "]";
                    adapter.Fill(ds, elt);
                }

                //requête sql pour récupérer la table transaction, ainsi que le type de la transaction via une jointure
                string sqlTransaction = @"SELECT t.codeTransaction, t.dateTransaction, t.description, t.montant, t.recetteON, t.percuON, t2.libType 
                               FROM [Transaction] t INNER JOIN [TypeTransaction] t2 ON t.type = t2.codeType
                               ORDER BY t.dateTransaction";

                cmd.CommandText = sqlTransaction;
                adapter.Fill(ds, "Transaction");

                //paramétrages du bindingsource
                transactionsBS.DataSource = ds.Tables["Transaction"];

                lblType.DataBindings.Add(new Binding("text", transactionsBS, "libType"));
                lblMontant.DataBindings.Add(new Binding("Text", transactionsBS, "montant"));

                //date de la transaction + format it
                lblDate.DataBindings.Add(
                    new Binding("Text", transactionsBS, "dateTransaction",
                                true, DataSourceUpdateMode.Never, (object)DBNull.Value, Program.settings.localize.Translate("dd/MM/yyyy"))
                    );

                //description de la transaction
                rtxtDescription.DataBindings.Add(new Binding("Text", transactionsBS, "description"));

                //percu
                chkPercu.DataBindings.Add(new Binding("checked", transactionsBS, "percuON"));

                //recette
                chkRecette.DataBindings.Add(new Binding("checked", transactionsBS, "recetteON"));

                //page de la transaction
                lblPage.Text = string.Format(Program.settings.localize.Translate("page_{0}_of_{1}"),
                                             transactionsBS.Position + 1, transactionsBS.Count);

                //on regarde quelles personnes sont concernées par la transaction
                updatePersonnes();
            }
            catch (OleDbException exc)
            {
                ErrorManager.HandleOleDBError(exc);
            }
            finally
            {
                connec.Close();
            }
        }
Пример #25
0
        ////////// Partie recherche //////////////////////////////////////////
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string       requete = @"SELECT * FROM [Transaction] ";
            OleDbCommand cmd     = new OleDbCommand();

            cmd.Connection = DatabaseManager.GetConnection();

            // Si rechercher par Date Unique
            if (ckbDate.Checked && rdbDateUnique.Checked)
            {
                string date = dtpDeb.Value.ToShortDateString();
                if (!requete.Contains("WHERE"))
                {
                    requete += "WHERE [dateTransaction] = @dateUniq ";
                }
                else
                {
                    requete += "AND [dateTransaction] = @dateUniq ";
                }
                cmd.Parameters.AddWithValue("@dateUniq", date);
            }
            // Si recherche par Plage de date
            else if (ckbDate.Checked && rdbPlage.Checked)
            {
                string dateDeb = dtpDeb.Value.ToShortDateString();
                string dateFin = dtpFin.Value.ToShortDateString();
                if (!requete.Contains("WHERE"))
                {
                    requete += "WHERE [dateTransaction] >= @dateDebut " +
                               "AND [dateTransaction] <= @dateFin ";
                }
                else
                {
                    requete += "AND [dateTransaction] >= @dateDebut " +
                               "AND [dateTransaction] <= @dateFin ";
                }
                cmd.Parameters.AddWithValue("@dateDebut", dateDeb);
                cmd.Parameters.AddWithValue("@dateFin", dateFin);
            }
            // Si recherche par libellé
            if (ckbLib.Checked)
            {
                string libelle = txtLib.Text;
                if (!requete.Contains("WHERE"))
                {
                    requete += "WHERE [description] LIKE @description ";
                }
                else
                {
                    requete += "AND [description] LIKE @description ";
                }
                cmd.Parameters.AddWithValue("@description", "%" + libelle + "%");
            }
            // Si recherche par montant
            if (ckbMontant.Checked)
            {
                string montant = txtMontant.Text;
                if (!requete.Contains("WHERE"))
                {
                    requete += "WHERE [montant] & '' LIKE @montant ";
                }
                else
                {
                    requete += "AND [montant] & '' LIKE @montant ";
                }
                cmd.Parameters.AddWithValue("@montant", "%" + montant + "%");

                // Bouton recette
                requete += "AND [recetteON] = @recetteStatu ";
                cmd.Parameters.AddWithValue("@recetteStatu", ckbRecette.Checked);

                // Bouton percu
                requete += "AND [percuON] = @percuStatu ";
                cmd.Parameters.AddWithValue("@percuStatu", ckbPercu.Checked);
            }

            cmd.CommandText = requete;

            try
            {
                cmd.Connection.Open();

                // On créé une table pour stocker les résultats
                DataTable        dtResults = new DataTable("tblResults");
                OleDbDataAdapter daResults = new OleDbDataAdapter(cmd);
                // On remplit cette table avec la requête de recherche construite ci-dessus
                daResults.Fill(dtResults);
                // Si aucune ligne n'a été trouvé, on vide le dgv et on affiche une message
                if (dtResults.Rows.Count == 0)
                {
                    dgvTransac.DataSource = null;
                    MessageBox.Show(Program.settings.localize.Translate("err_no_transaction_found_msg"),
                                    Program.settings.localize.Translate("warning"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                // Sinon, on affiche les résultats
                else
                {
                    dgvTransac.DataSource = dtResults;
                }
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                cmd.Connection.Close();
            }
        }
Пример #26
0
        public void PrintToPDDF(int month, int year)
        {
            int i;
            int entry_index;

            TransactionRepository.TransactionModel[] _transactions = null;

            // the sum of every transaction in the current groupe
            decimal group_total;
            decimal group_spendings;
            decimal group_received_incomes;
            decimal group_pending_incomes;

            // the sum of every group's amount
            decimal total_amount           = 0.0M;
            decimal total_spendings        = 0.0M;
            decimal total_received_incomes = 0.0M;
            decimal total_pending_incomes  = 0.0M;

            // a temporary set of HTML rows
            StringBuilder currentEntryRow_str;

            // prepare the base document
            PdfDocument doc = new PdfDocument();

            // retrieve every transaction of the current month
            try
            {
                _transactions = TransactionRepository.GetByMonth(month, year);
            }
            catch (OleDbException ex)
            {
                // abort if there was an error
                ErrorManager.HandleOleDBError(ex);
                return;
            }

            // Group each transaction by type
            IGrouping <int, TransactionRepository.TransactionModel>[] transactionsGroups = _transactions.GroupBy(x => x.type).ToArray();

            // the HTML headings
            StringBuilder s = new StringBuilder(@"<!DOCTYPE html>
            <html>
                <head>
                    <meta charset='utf-8' />
                    <title></title>"
                                                );

            GetCSSMeta(s);

            GetPageTitle(month, _transactions.Length, s);

            // Table header's row
            s.Append(@"
                </head>
                <body><table>
            ");

            i = 0;
            foreach (IGrouping <int, TransactionRepository.TransactionModel> transactions in transactionsGroups)
            {
                ++i;
                entry_index = 0;

                group_total            = 0.0M;
                group_spendings        = 0.0M;
                group_received_incomes = 0.0M;
                group_pending_incomes  = 0.0M;

                currentEntryRow_str = new StringBuilder();

                var it = transactions.GetEnumerator();

                while (it.MoveNext())
                {
                    ++entry_index;

                    currentEntryRow_str.AppendFormat(@"
                        <tr>
                            <td>{0}</td>
                            <td class='amount'>{1}</td>
                            <td class='{2}'></td>
                            <td class='{3}'></td>
                            <td class='left'>{4}</td>
                        </tr>
                        ",
                                                     it.Current.dateTransaction.ToString(Program.settings.localize.Translate("dd/MM/yyyy")),
                                                     it.Current.montant,
                                                     it.Current.recetteON ? "yes" : "no",
                                                     it.Current.percuON ? "yes" : "no",
                                                     string.IsNullOrWhiteSpace(it.Current.description) ? "-" : it.Current.description
                                                     );

                    // if it is an income
                    if (it.Current.recetteON)
                    {
                        // look if he received the income or not and append it
                        if (it.Current.percuON)
                        {
                            group_received_incomes += it.Current.montant;

                            // add the income the group income
                            group_total += it.Current.montant;
                        }
                        else
                        {
                            group_pending_incomes = it.Current.montant;
                        }
                    }
                    // otherwise, it is a spending, a loss.
                    else
                    {
                        group_spendings += it.Current.montant;

                        // if the value is negative, make it positive
                        group_total -= it.Current.montant > 0 ? it.Current.montant : it.Current.montant * -1;
                    }
                }

                s.AppendFormat(@"
                    <tr><td class='hr' colspan='5'></td></tr>
                    <tr>
                        <th colspan='5' class='th-line-title'>
                            <h2 style='margin: 0'>{0}</h2>
                            {1}, <span class='amount'>{2}</span>
                        </th>
                    </tr>
                ", it.Current.typeTransaction_s, FormatTransactionCount(entry_index), group_total);

                // if we are proceeding the first entry, append the legend
                if (i == 1)
                {
                    s.AppendFormat(@"
                    <tr>
                        <th>{0}</th>
                        <th>{1}</th>
                        <th>{2}</th>
                        <th>{3}</th>
                        <th width='100%'>{4}</th>
                    </tr>",
                                   Program.settings.localize.Translate("transaction_date"),
                                   Program.settings.localize.Translate("amount"),
                                   Program.settings.localize.Translate("income"),
                                   Program.settings.localize.Translate("received"),
                                   Program.settings.localize.Translate("description")
                                   );
                }

                // append the entries
                s.Append(currentEntryRow_str);

                total_amount           += group_total;
                total_pending_incomes  += group_pending_incomes;
                total_received_incomes += group_received_incomes;
                total_spendings        += group_spendings;
            }

            s.AppendFormat(@"
                    </table>
                    <hr/>
                    <table class='bold-table'>
                        <tr>
                            <td>Dépenses</td>
                            <td class='amount'>{0}</td>
                        </tr>

                        <tr>
                            <td>Recettes</td>
                            <td class='amount'>{1}</td>
                        </tr>

                        <tr>
                            <td>À percevoir</td>
                            <td class='amount'>{2}</td>
                        </tr>

                        <tfoot>
                            <tr>
                                <td>Total</td>
                                <td class='amount'>{3}</td>
                            </tr>
                        </tfoot>
                    </table>
                </body>
            </html>", total_spendings, total_received_incomes, total_pending_incomes, total_amount);

            // set the default filename
            saveFileDialog.FileName = GetFileNameFromMonth(month);

            // ask where to save the PDF file
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                doc.Html = s.ToString();
                WkHtmlWkHtmlPdfConverter.ConvertHtmlToPdf(doc, saveFileDialog.FileName);

                // open the PDF file
                Process.Start(saveFileDialog.FileName);
            }
        }
Пример #27
0
        private void btnValiderBudgetPonctuel_Click(object sender, EventArgs _ev)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // Will store the deadlines
            List <KeyValuePair <DateTime, decimal> > deadLines;

            // Retrieve the budget's title + comments and remove any leading whitespacess
            string budgetTitle    = this.txtBoxIntitulePonctuel.Text.Trim();
            string budgetComments = this.txtBoxCommentairePonctuel.Text.Trim();

            // if the comments are empty, set it to null (to avoid a OleDB Error)
            if (string.IsNullOrEmpty(budgetComments))
            {
                budgetComments = null;
            }

            // TODO: if set, check if the sum of the fields is equal to the input sum
            //		 if not, put a warning & ask for confirmation
            //    string.IsNullOrEmpty(this.txtBoxMontantPonctuel.Text)
            //    && float.TryParse(this.txtBoxMontantPonctuel.Text, out montantTotal)

            // - if:
            //     - the budget's title is null/empty
            //     - or only has spaces:
            //     - or if not every deadline is filled
            //   ---> show missing fields error and stop proceeding
            //
            // - otherwise: proceed and insert the data (if the title does not exist yet)

            if (string.IsNullOrWhiteSpace(budgetTitle) ||
                this.numberOfDeadlines < 1

                // try to retrieve every deadlines, store it to `deadLines` and return false
                // if there was a missing value
                || !CheckAndConvertDeadLinesToList(out deadLines))
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }

            // check if the budgetTitle is unique in the database
            // if not unique: show an error saying that it already exists and stop proceeding
            try {
                if (!PosteRepository.IsUnique(budgetTitle))
                {
                    // show a duplicate value error and specify the field
                    ErrorManager.ShowDuplicateError(this,
                                                    Program.settings.localize.Translate(this.lblIntitulePonctuel.Name));
                    return;
                }
            } catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
                return;
            }

            // otherwise: continue and insert the data
            dbConn = DatabaseManager.GetConnection();

            dbConn.Open();

            dbTransaction = dbConn.BeginTransaction();

            // Insert the data to the data base
            try {
                PostePonctuelRepository.Create(dbConn, dbTransaction,
                                               budgetTitle,
                                               budgetComments,
                                               deadLines.ToArray()
                                               );

                Console.WriteLine("<- Commit");
                dbTransaction.Commit();

                ErrorManager.EntriesSuccessfullyAdded(this);
                ClearPostePonctuelForm();
            } catch (OleDbException e)
            {
                // cancel the changes
                dbTransaction.Rollback();

                // handle the error (log it and report it to the user)
                ErrorManager.HandleOleDBError(e);
            }
            finally
            {
                dbConn.Close();
            }
        }