コード例 #1
0
        private void btnExport_Click(object sender, System.EventArgs e)
        {
            int year;

            if (!LocalizationManager.ConvertFloatingTo <int>(this.txtBoxYear.Text, int.TryParse, out year))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // this code spawned itself from nowhere idk why
            try {
                if (year == 666)
                {
                    throw new UnableToSummonDaCatException();
                }
            }
            catch (UnableToSummonDaCatException ex)
            {
                ErrorManager.HandleBaseException(ex);
                return;
            }

            PrintToPDDF(this.comboBoxMonth.SelectedIndex + 1, year);
        }
コード例 #2
0
        private void Submit_Click(object sender, EventArgs _e)
        {
            decimal montant;
            int     everyXDays;

            PeriodiciteRepository.PeriodiciteModel period;

            try {
                PosteRepository.CheckDayRangeOrThrow(int.Parse(this.TxtBoxTousLesXMois.Text));
            }
            catch (ArgumentException e)
            {
                ErrorManager.ShowOperationFailed(this, e.Message);
                return;
            }

            // check if fields not empty
            if (string.IsNullOrWhiteSpace(this.txtBoxLibPoste.Text) ||
                string.IsNullOrWhiteSpace(TxtBoxTousLesXMois.Text) ||
                string.IsNullOrWhiteSpace(this.TxtBoxMontantPosteFixe.Text) ||
                this.ComboxBoxListePeriodicites.SelectedItem == null)
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }

            // check if values are valid
            if (!(LocalizationManager.ConvertFloatingTo <int>(
                      this.TxtBoxTousLesXMois.Text, int.TryParse, out everyXDays) &&
                  LocalizationManager.ConvertFloatingTo <decimal>(
                      this.TxtBoxMontantPosteFixe.Text, decimal.TryParse, out montant)))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            editedData.libPoste_s = this.txtBoxLibPoste.Text;

            // if the lib poste was modified, check if unique; if not => error
            if (!originalData.libPoste_s.Equals(editedData.libPoste_s) &&
                !PosteRepository.IsUnique(editedData.libPoste_s))
            {
                ErrorManager.ShowDuplicateError(this);
                return;
            }

            period = (PeriodiciteRepository.PeriodiciteModel) this.ComboxBoxListePeriodicites.SelectedItem;

            // retrieve/ set remaining data
            editedData.jourDuMois = everyXDays;
            editedData.montant    = montant;
            editedData.typePer    = period.codePer;
            editedData.libPer_s   = period.libPer;

            // mark form as submitted and close it
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
コード例 #3
0
        private void lblConfirmMontantPonctuel_Click(object sender, EventArgs e)
        {
            int     nbPrelevements;
            decimal montantTotal;

            // generates deadlines
            lblConfirmNbDeadLines_Click(sender, e);

            // if the values are not number: show error
            if (!LocalizationManager.ConvertFloatingTo <int>(this.txtBoxNbPrelevementsPonctuel.Text, int.TryParse, out nbPrelevements) ||
                !LocalizationManager.ConvertFloatingTo <decimal>(this.txtBoxMontantPonctuel.Text, decimal.TryParse, out montantTotal))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            if (ArePonctuelAmountFieldsInvalid())
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }
        }
コード例 #4
0
        /// <summary>
        /// </summary>
        /// <returns>
        /// Returns false if there was a missing data.
        /// </returns>
        private bool CheckAndConvertDeadLinesToList(out List <KeyValuePair <DateTime, decimal> > deadLines_list)
        {
            decimal amount;
            KeyValuePair <DateTimePicker, MetroTextBox> e;

            deadLines_list = new List <KeyValuePair <DateTime, decimal> >();

            // go through every deadlines
            // (we don't use a foreach(...) because, we don't remove every deadline if the user
            // edit the deadline count to a lower value as before.
            // We only hide them for performance issues. But we don't proceed them.)
            int i = 0;

            while (i < this.numberOfDeadlines)
            {
                // retrieve the entry (DatePicker & TextBox)
                e = this.txtEcheancePonctuelsEntries[i];

                // try to convert the textbox value to decimal
                // if we fail, we log it
                // then we return false and stop proceeding
                if (!LocalizationManager.ConvertFloatingTo <decimal>(e.Value.Text, decimal.TryParse, out amount))
                {
                    Console.WriteLine("F :: Unable to convert {0} ;; {1} to decimal", e.Value, e.Value.Name);
                    return(false);
                }

                // otherwise, we append it to the deadline list
                deadLines_list.Add(new KeyValuePair <DateTime, decimal>(
                                       e.Key.Value, // datetime
                                       amount
                                       ));

                ++i;
            }
            return(true);
        }
        // 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
        }
コード例 #6
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();
            }
        }
コード例 #7
0
        /*
         * Is called when the value of the input field of the number of deductions is changed.
         *
         * - If the input number is greater than the previously generated one:
         *	 we create more input fields.
         *
         * - If the number of visible fields is less than the number of deadlines:
         *   toggle the needed ones to visible.
         * - Else (greater), toggle them to invisible.
         */
        private void lblConfirmNbDeadLines_Click(object sender, EventArgs e)
        {
            FlowLayoutPanel newDeadlineContainer;
            int             newDeadlineCount;
            decimal         montantTotal;

            if (!LocalizationManager.ConvertFloatingTo <int>(this.txtBoxNbPrelevementsPonctuel.Text, int.TryParse, out newDeadlineCount) || newDeadlineCount < 1)
            {
                this.errorProvider.SetError(this.txtBoxNbPrelevementsPonctuel,
                                            Program.settings.localize.Translate("err_not_a_valid_number"));
                return;
            }


            // if the new deadline count is the same than the previous one,
            // change nothing (don't try to add or remove things).
            if (newDeadlineCount != this.numberOfDeadlines)
            {
                // if the number of the alrady created deadlines is less than the entered count,
                // create them.
                if (this.txtEcheancePonctuelsEntries.Count < newDeadlineCount)
                {
                    // put the main container visible
                    this.echancesContainer.Visible = true;

                    for (int c = this.txtEcheancePonctuelsEntries.Count + 1; c <= newDeadlineCount; ++c)
                    {
                        // generate a (visible) deadline container
                        newDeadlineContainer = this.CreateDeadlineContainer(c);

                        // Append the newly created deadline container to the container list
                        this.containerEchancesPonctuelles.Controls.Add(newDeadlineContainer);
                    }
                }

                // XXX: I should refactor that ugly pill of crap
                for (int i = newDeadlineCount; i < this.txtEcheancePonctuelsEntries.Count; ++i)
                {
                    this.txtEcheancePonctuelsEntries[i].Value.Parent.Visible = false;
                }
                for (int i = 0; i < newDeadlineCount; ++i)
                {
                    this.txtEcheancePonctuelsEntries[i].Value.Parent.Visible = true;
                }

                // update the number of deadlines
                this.numberOfDeadlines = newDeadlineCount;
            }

            // Unset the error provider and tell the async blinker
            // to stop blinking the confirmation labels
            this.errorProvider.SetError(this.txtBoxNbPrelevementsPonctuel, "");
            this.stopBlinkingPunctualAmount = true;

            // If there was a amount entered:
            //   ask if the user wants to override the deadlines
            //   with the amount divided the deadlines number.
            if (!string.IsNullOrWhiteSpace(this.txtBoxMontantPonctuel.Text) &&
                LocalizationManager.ConvertFloatingTo <decimal>(this.txtBoxMontantPonctuel.Text, decimal.TryParse, out montantTotal))
            {
                AskToUpdateDeadLinesFromAmount(montantTotal, newDeadlineCount);
            }
        }
コード例 #8
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();
            }
        }
コード例 #9
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;
        }