private void btnValider_Click(object sender, EventArgs e) { try { if (grilleDemande.SelectedCells[0].Value.ToString() != "") { String Cin = grilleDemande.SelectedCells[0].Value.ToString(); String Type = grilleDemande.SelectedCells[1].Value.ToString(); DateTime DateDemande = Convert.ToDateTime(grilleDemande.SelectedCells[2].Value); //L'appel de la méthode MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Voulez-vous vraiment valider cette demande."); message.ShowDialog(); if (message.DialogResult == System.Windows.Forms.DialogResult.OK) { Controllers.DemandeController.ModifierNouveauDemande(Cin, Type, DateDemande, ref grilleDemande); } } } catch (Exception) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Aucune demande n'est séléctionner"); message.ShowDialog(); } }
//Ajouter une nouveau type public static void AjouterType(String Type, String Droits) { //Ajouter les données Congé conge = new Congé(Type, Droits); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Nouveau type ajouter avec succé."); message.ShowDialog(); }
//Enregistrement de la demande public static void EnregistrerDemande(String CIN, String Type, DateTime DateDebut, DateTime DateFin, String Commentaire) { Int32 NombreJours = Convert.ToInt32((DateFin.Date - DateDebut.Date).TotalDays); //Enregistremet des données Demande demande = new Demande(CIN, Type, DateTime.Now, DateDebut, DateFin, NombreJours, Commentaire); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Votre demande ajouter avec succés."); message.ShowDialog(); }
private void btToArchiv_Click(object sender, EventArgs e) { if (trvPost.SelectedNode == null) { return; } object objSelectTag = trvPost.SelectedNode.Tag; if (objSelectTag == null) { return; } if (!(objSelectTag is Document)) { return; } if (!transferDoc.getStatusDocuments(((Document)objSelectTag).id_document, 3)) { return; } //if (!transferDoc.setStatusDocument(((Document)objSelectTag).id_document, 4)) return; DialogResult dlgResult = new MyMessageBox.MyMessageBox("Вы хотите заменить помещаемый\n\"В архив\" документ на новый?", "Перевод документа в архив", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string> { "Да, заменить на новый", "Нет, не заменять", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.Cancel) { return; } if (DialogResult.OK == new ArchiveDocAddDoc.justification.frmAdd() { id_Document = ((Document)objSelectTag).id_document }.ShowDialog()) { } if (DialogResult.Yes == dlgResult) { if (DialogResult.OK == new ArchiveDocAddDoc.frmAddDoc() { Text = "Добавление документа", id_new = ((Document)objSelectTag).id_document }.ShowDialog()) { getDataDocuments(); } } getDataDocuments(); }
private void btnAjouter_Click(object sender, EventArgs e) { //valdiation des données bool etat = false; Controllers.PersonnelController.ValiderDonner(txtCin, txtNom, txtPrénom, txtDN, comboSexe, txtTelephone, txtAdresse, comboFonction, txtEmail, txtLogin, txtMdp, txtConfirmationMdp, out etat); if (etat) { Personnel personnel = new Personnel(txtCin.Text, txtNom.Text, txtPrénom.Text, Convert.ToDateTime(txtDN.Text), comboSexe.SelectedText, txtTelephone.Text, txtAdresse.Text, txtLogin.Text, comboFonction.SelectedText, txtEmail.Text, txtMdp.Text); MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Le nouveau personnel est ajouter avec succé."); message.ShowDialog(); } }
//Valider les demandes (Modifier) public static void ModifierNouveauDemande(String Cin, String Type, DateTime DateDemande, ref DataGridView Grille) { Demande demande = new Demande(); demande.ModifierDemande(Cin, Type, DateDemande); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "La demande à été valider avec succés."); message.ShowDialog(); //vider la grille Grille.Rows.Clear(); //remplire la grille DemandeController.AfficherDemandeInvalide(ref Grille); }
//Annuler une demande public static void AnnulerDemande(String CIN, String Type, DateTime DateDemande, ref DataGridView Grille) { Demande demande = new Demande(); demande.AnnulerDemande(CIN, Type, DateDemande); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "La demande à été annuler avec succés."); message.ShowDialog(); //vider la grille Grille.Rows.Clear(); //remplire la grille DemandeController.AfficherDemandeAnnuler(CIN, ref Grille); }
//supprimer un perosnnel public static void SupprimerPersonnel(String CIN, ref DataGridView Grille) { Personnel personne = new Personnel(); personne.SupprimerPersonnel(CIN); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Le personnel est supprimer avec succés."); message.ShowDialog(); //vider la grille Grille.DataSource = null; //remplire la grille PersonnelController.AfficherPersonnels(ref Grille); }
private void btDown_Click(object sender, EventArgs e) { if (trvPost.SelectedNode == null) { return; } object objSelectTag = trvPost.SelectedNode.Tag; if (objSelectTag == null) { return; } if (!(objSelectTag is Document)) { return; } if (!transferDoc.getStatusDocuments(((Document)objSelectTag).id_document, 2)) { return; } DialogResult dlgResult = new MyMessageBox.MyMessageBox("Вы хотите отозвать документ\n\"На ознакомление\" и сделать статус \"Новый\"?", "Отозвать документ", MyMessageBox.MessageBoxButtons.YesNo, new List <string> { "Да, отозвать", "Нет, не отзывать", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.No) { return; } if (DialogResult.OK == new ArchiveDocAddDoc.redoDocument.frmAdd() { id_Document = ((Document)objSelectTag).id_document }.ShowDialog()) { getDataDocuments(); } //if (!transferDoc.setStatusDocument(((Document)objSelectTag).id_document, 1)) return; }
private void btNext_Click(object sender, EventArgs e) { if (trvPost.SelectedNode == null) { return; } object objSelectTag = trvPost.SelectedNode.Tag; if (objSelectTag == null) { return; } if (!(objSelectTag is Document)) { return; } if (!transferDoc.getStatusDocuments(((Document)objSelectTag).id_document, 1)) { return; } DialogResult dlgResult = new MyMessageBox.MyMessageBox("Вы хотите передать документ\n\"На ознакомление\"?", "Передать документ на ознакомление", MyMessageBox.MessageBoxButtons.YesNo, new List <string> { "Да", "Нет", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.No) { return; } if (!transferDoc.setStatusDocument(((Document)objSelectTag).id_document, 2)) { return; } getDataDocuments(); }
private void btnSupprimer_Click(object sender, EventArgs e) { try { if (grillePersonnels.SelectedCells[0].Value.ToString() != "") { String Cin = grillePersonnels.SelectedCells[0].Value.ToString(); //Message MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Information", "Voulez-vous annuler supprimer ce personnel?"); message.ShowDialog(); if (message.DialogResult == System.Windows.Forms.DialogResult.OK) { //L'appel de la méthode Controllers.PersonnelController.SupprimerPersonnel(Cin, ref grillePersonnels); } } } catch (Exception) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Aucun personnel n'est séléctionner"); message.ShowDialog(); } }
private void btNext_Click(object sender, EventArgs e) { if (trvPost.SelectedNode == null) { return; } object objSelectTag = trvPost.SelectedNode.Tag; if (objSelectTag == null) { return; } if (!(objSelectTag is Document)) { return; } //if (!transferDoc.getStatusDocuments(((Document)objSelectTag).id_document, 1)) return; DialogResult dlgResult = new MyMessageBox.MyMessageBox("Вы хотите установить статус документа на \n\"Ознакомлен\"?", "Ознакомление с документов", MyMessageBox.MessageBoxButtons.YesNo, new List <string> { "Да", "Нет", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.No) { return; } if (!transferDoc.setStatusSingleDocument(((Document)objSelectTag).id_document, ((Document)objSelectTag).id_documentVsPost, 3)) { return; } getDataDocuments(); }
//Validation des zones de texte public static void ValiderZone(TextBox txtType, TextBox txtDroit, out bool etat) { etat = false; if (txtType.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer un nouveau type."); message.ShowDialog(); txtType.Focus(); txtType.SelectAll(); return; } if (txtDroit.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer des droits valides."); message.ShowDialog(); txtDroit.Focus(); txtDroit.SelectAll(); return; } etat = true; }
//Validation des zones public static void ValidationZone(MaskedTextBox DateDebut, MaskedTextBox DateFin, TextBox Commentaire, CheckBox Confirmation, out bool etat) { etat = false; if (!DateDebut.MaskCompleted) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer la date de debut de congé."); message.ShowDialog(); DateDebut.Focus(); DateDebut.SelectAll(); return; } if (!DateFin.MaskCompleted) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer la date de fin de congé."); message.ShowDialog(); DateFin.Focus(); DateFin.SelectAll(); return; } if (DateDebut.MaskCompleted && DateFin.MaskCompleted) { DateTime Debut, Fin; if (!DateTime.TryParse(DateDebut.Text, out Debut)) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer une date valide."); message.ShowDialog(); DateDebut.Focus(); DateDebut.SelectAll(); return; } if (!DateTime.TryParse(DateFin.Text, out Fin)) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer une date valide."); message.ShowDialog(); DateFin.Focus(); DateFin.SelectAll(); return; } Debut = DateTime.Parse(DateDebut.Text); Fin = DateTime.Parse(DateFin.Text); if (DateTime.Now.Date > Debut.Date) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer une date valide."); message.ShowDialog(); DateDebut.Focus(); DateDebut.SelectAll(); return; } if (Debut.Date > Fin.Date) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "La date de debut est inférieur que la date de fin."); message.ShowDialog(); DateFin.Focus(); DateFin.SelectAll(); return; } } if (Commentaire.Text == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer la raison de congé."); message.ShowDialog(); Commentaire.Focus(); Commentaire.SelectAll(); return; } if (!Confirmation.Checked) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez confirmer la demande."); message.ShowDialog(); return; } etat = true; }
private void btSave_Click(object sender, EventArgs e) { DataTable dtResult; DateTime _startDate = new DateTime(dtpStart.Value.Year, dtpStart.Value.Month, 1); int _id = id; Task <DataTable> task = Config.hCntMain.getTPlanReport(_startDate.Date, _startDate.Date, (int)cmbObject.SelectedValue); task.Wait(); if (task.Result != null && task.Result.Rows.Count > 0) { _id = (int)task.Result.Rows[0]["id"]; MyMessageBox.MyMessageBox mmb = new MyMessageBox.MyMessageBox($"За выбранный период для объекта:\n\"{cmbObject.Text}\"\nуже создан ежемесячный план на {dtpStart.Text}.\nПерезаписать существующий план?", "", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string> { "Да", "Нет", "Отмена" }); DialogResult dlgResult = mmb.ShowDialog(); if (dlgResult == DialogResult.Cancel) { return; } if (dlgResult == DialogResult.No) { dgvData.DataSource = null; dtData.Clear(); setFilter(); statusElements(true); isChangeValue = false; return; } if (dlgResult == DialogResult.Yes) { task = Config.hCntMain.setTPlanReport(_id, _startDate.Date, (int)cmbObject.SelectedValue, false, true, 0); task.Wait(); dtResult = task.Result; if (dtResult == null || dtResult.Rows.Count == 0) { MessageBox.Show("Не удалось сохранить данные", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -2) { MessageBox.Show(Config.centralText("Данный план подтверждён.\nПерезапись невозможна!\n"), "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -9999) { MessageBox.Show("Ошибка выполнения процедуры", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //task = Config.hCntMain.setTPlanReport(_id, _startDate.Date, (int)cmbObject.SelectedValue, false, true, 1); task = Config.hCntMain.spg_setPlanReport(_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, true); task.Wait(); } } task = Config.hCntMain.setTPlanReport(id, _startDate.Date, (int)cmbObject.SelectedValue, false, false, 0); task.Wait(); dtResult = task.Result; if (dtResult == null || dtResult.Rows.Count == 0) { MessageBox.Show("Не удалось сохранить данные", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -9999) { MessageBox.Show("Ошибка выполнения процедуры", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } id = (int)dtResult.Rows[0]["id"]; foreach (DataRow row in dtData.Rows) { task = Config.hCntMain.spg_setPlanReport( id , (int)row["id"] , (decimal)row["Total_Sum"] , (decimal)row["Discount"] , (decimal)row["sumPayCont"] , (decimal)row["EndPlan"] , (decimal)row["Penalty"] , (decimal)row["OtherPayments"] , (decimal)row["ultraResult"] , (decimal)row["Included"] , (decimal)row["Credit"] , (decimal)row["OverPayment"] , false); task.Wait(); dtResult = task.Result; if (dtResult == null || dtResult.Rows.Count == 0) { MessageBox.Show("Не удалось сохранить данные", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -9999) { MessageBox.Show("Ошибка выполнения процедуры", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } Logging.StartFirstLevel(row == null ? (int)logEnum.Добавление_план_отчета : (int)logEnum.едактирование_план_отчета); Logging.Comment($"ID:{id}"); Logging.Comment($"Период плана:{dtpStart.Value.ToShortDateString()}"); Logging.Comment("id объекта = " + cmbObject.SelectedValue.ToString() + ", Наименование объекта : \"" + cmbObject.Text.ToString() + "\""); Logging.Comment("Информация по договорам"); foreach (DataRow row in dtData.Rows) { Logging.Comment($"Id договора:{row["id"]}"); Logging.Comment($"Арендодатель:{row["nameLandLord"]}"); Logging.Comment($"Арендатор:{row["nameTenant"]}"); Logging.Comment($"Номер договора:{row["Agreement"]}"); Logging.Comment($"Срок действия:{row["timeLimit"]}"); Logging.Comment($"Здание:{row["Build"]}"); Logging.Comment($"Этаж:{row["Floor"]}"); Logging.Comment($"№ секции:{row["namePlace"]}"); Logging.Comment($"Площадь м2:{row["Total_Area"]}"); Logging.Comment($"Стоимость м2:{row["Cost_of_Meter"]}"); Logging.Comment($"Сумма по договору:{row["Total_Sum"]}"); Logging.Comment($"Скидка:{row["Discount"]}"); Logging.Comment($"Обеспечительный платеж:{row["sumPayCont"]}"); Logging.Comment($"Долг за предыдущий период:{row["preCredit"]}"); Logging.Comment($"Переплата за предыдущий период:{row["preOverPayment"]}"); Logging.Comment($"План на начало:{row["prePlan"]}"); Logging.Comment($"План на конец:{row["EndPlan"]}"); Logging.Comment($"Пени:{row["Penalty"]}"); Logging.Comment($"Прочие платежи:{row["OtherPayments"]}"); Logging.Comment($"Всего к оплате:{row["ultraResult"]}"); Logging.Comment($"Внесено:{row["Included"]}"); Logging.Comment($"Долг:{row["Credit"]}"); Logging.Comment($"Переплата:{row["OverPayment"]}"); } Logging.StopFirstLevel(); MessageBox.Show("Данные сохранены.", "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Information); isChangeValue = false; this.DialogResult = DialogResult.OK; }
//validation des entrés public static void ValiderDonner(TextBox txtCIN, TextBox txtNom, TextBox txtPrenom, MaskedTextBox txtDN, ComboBox comboSexe, TextBox txtTél, TextBox txtAdresse, ComboBox comboFonction, TextBox txtEmail, TextBox txtLogin, TextBox txtMDP, TextBox txtMDPC, out bool etat) { //variable locale DateTime date; Regex emailRegex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); //regex pour valider le format d'email etat = false; if (txtCIN.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le CIN."); message.ShowDialog(); txtCIN.Focus(); txtCIN.SelectAll(); return; } if (txtNom.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le Nom."); message.ShowDialog(); txtNom.Focus(); txtNom.SelectAll(); return; } if (txtPrenom.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le Prénom."); message.ShowDialog(); txtPrenom.Focus(); txtPrenom.SelectAll(); return; } if (!DateTime.TryParse(txtDN.Text, out date) || Convert.ToDateTime(txtDN.Text) >= DateTime.Now) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer une date valide."); message.ShowDialog(); txtDN.Focus(); txtDN.SelectAll(); return; } if (comboSexe.SelectedIndex < 0) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez selectionner le sexe."); message.ShowDialog(); comboSexe.Focus(); return; } if (txtTél.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le Téléphone."); message.ShowDialog(); txtTél.Focus(); txtTél.SelectAll(); return; } if (txtAdresse.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer l'Adresse."); message.ShowDialog(); txtAdresse.Focus(); txtAdresse.SelectAll(); return; } if (comboFonction.SelectedIndex < 0) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez selectionner la fonction."); message.ShowDialog(); comboFonction.Focus(); return; } if (txtEmail.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer l'Adresse email."); message.ShowDialog(); txtEmail.Focus(); txtEmail.SelectAll(); return; } if (emailRegex.IsMatch(txtEmail.Text) == false) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Adresse email invalide."); message.ShowDialog(); txtEmail.Focus(); txtEmail.SelectAll(); return; } if (txtLogin.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le Login."); message.ShowDialog(); txtLogin.Focus(); txtLogin.SelectAll(); return; } if (txtMDP.Text.Trim() == "") { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer le Mot de passe."); message.ShowDialog(); txtMDP.Focus(); txtMDP.SelectAll(); return; } if (txtMDPC.Text != txtMDP.Text) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Veuillez entrer un Mot de passe valide."); message.ShowDialog(); txtMDP.Focus(); txtMDP.SelectAll(); txtMDPC.Focus(); txtMDPC.SelectAll(); return; } etat = true; }
private void btnConnexion_Click(object sender, EventArgs e) { try {//Authentification Personnel if (radioPersonnel.Checked && !radioResponsable.Checked) { //validation des champs bool etat; AuthentificationController.ValiderChamps(ref txtLogin, ref txtPasse, out etat); //si y'as des erreurs on est besoin de faire quitter la procedure if (etat == false) { return; } //Obtenir la valuer de la zone login Login = txtLogin.Text; //authentification Models.Authentification login = new Models.Authentification(txtLogin.Text, txtPasse.Text, "Personnel"); //validation des champs if (Models.Authentification.num >= 1) { //fermer le formulaire d'authentification pour ne pas chargé la ram this.Close(); //ouvrire le nouveau formulaire Thread thread = new Thread(TableauBordPersonnel); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } else { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Compte invalide."); message.ShowDialog(); } } else if (!radioPersonnel.Checked && radioResponsable.Checked) { //validation des champs bool etat; AuthentificationController.ValiderChamps(ref txtLogin, ref txtPasse, out etat); //si y'as des erreurs on est besoin de faire quitter la procedure if (etat == false) { return; } //Obtenir la valuer de la zone login Login = txtLogin.Text; //authentification Models.Authentification login = new Models.Authentification(txtLogin.Text, txtPasse.Text, "Responsable"); //validation des champs if (Models.Authentification.num >= 1) { //fermer le formulaire d'authentification pour ne pas chargé la ram this.Close(); //ouvrire le nouveau formulaire Thread thread = new Thread(TableauBordResponsable); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } else { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Compte invalide."); message.ShowDialog(); } } else { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", "Choisir un radion bouton."); message.ShowDialog(); return; } } catch (Exception ex) { MyMessageBox.MyMessageBox message = new MyMessageBox.MyMessageBox("Erreur", ex.Message); message.ShowDialog(); } }
private void btSave_Click(object sender, EventArgs e) { if (cmbTypeDoc.SelectedIndex == -1) { MessageBox.Show($"Необходимо заполнить \"{lTypeDoc.Text}\"", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); cmbTypeDoc.Focus(); return; } if (fileBytes == null && id == 0) { MessageBox.Show($"Необходимо выбрать \"{lFileName.Text}\"", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); btAddDoc.Focus(); return; } if (tbNameDoc.Text.Trim().Length == 0) { MessageBox.Show($"Необходимо заполнить \"{lNameDoc.Text}\"", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); tbNameDoc.Focus(); return; } if (dtPostVsDeps == null) { MessageBox.Show("Нет данных по должностям.", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (dtPostVsDeps.Rows.Count == 0) { MessageBox.Show("Нет данных по должностям.", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } EnumerableRowCollection <DataRow> rowCollect = dtPostVsDeps.AsEnumerable().Where(r => r.Field <bool>("isSelect")); if (rowCollect.Count() == 0) { MessageBox.Show("Необходимо выбрать должность.", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } DialogResult dlgResult = new MyMessageBox.MyMessageBox("Выберите статус добавляемого документа:", "Добавление документа", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string> { "Новый", "На ознакомлении", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.Cancel) { return; } int id_status = 1; if (DialogResult.No == dlgResult) { id_status = 2; } Task <DataTable> task = Config.hCntMain.setDocuments(id, tbNameDoc.Text.Trim(), fileName, fileBytes, (int)cmbTypeDoc.SelectedValue, false, 0); task.Wait(); DataTable dtResult = task.Result; if (dtResult == null || dtResult.Rows.Count == 0) { MessageBox.Show("Не удалось сохранить данные", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -1) { MessageBox.Show("В базе данных уже присутствует документ с таким наименованием. Сохранение не возможно.", "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if ((int)dtResult.Rows[0]["id"] == -2) { MessageBox.Show(Config.centralText("Нет возможности сменить статус\nне соответствие условию смены\n!"), "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if ((int)dtResult.Rows[0]["id"] == -9999) { MessageBox.Show("Произошла неведомая хрень.", "Ошибка сохранения", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (id == 0) { id = (int)dtResult.Rows[0]["id"]; //Logging.StartFirstLevel(1); //Logging.Comment("Добавить Тип документа"); //Logging.Comment($"ID: {id}"); //Logging.Comment($"Наименование: {tbNameDoc.Text.Trim()}"); //Logging.Comment($"Номер по порядку: {tbNpp.Text.Trim()}"); //Logging.Comment($"Отображение архивных документов у руководителя: {(chbViewArchive.Checked ? "Да" : "Нет")}"); //Logging.Comment($"Отображать при добавлении документа: {(chbViewAdd.Checked ? "Да" : "Нет")}"); //Logging.StopFirstLevel(); } else { //Logging.StartFirstLevel(1); //Logging.Comment("Редактировать Тип документа"); //Logging.Comment($"ID: {id}"); //Logging.VariableChange("Наименование", tbNameDoc.Text.Trim(), oldName); //Logging.VariableChange("Номер по порядку", tbNpp.Text.Trim(), oldNpp); //Logging.VariableChange($"Отображение архивных документов у руководителя:", (chbViewArchive.Checked ? "Да" : "Нет"), (oldViewArchive ? "Да" : "Нет")); //Logging.VariableChange($"Отображать при добавлении документа:", (chbViewAdd.Checked ? "Да" : "Нет"), (oldViewAdd ? "Да" : "Нет")); //Logging.StopFirstLevel(); } foreach (int id_DocVsDepPosts in listDelPost) { task = Config.hCntMain.setDocuments_vs_DepartmentsPosts(id_DocVsDepPosts, "", "", 0, id, id_status, false, true, 1); task.Wait(); } foreach (DataRow row in rowCollect) { task = Config.hCntMain.setDocuments_vs_DepartmentsPosts((int)row["id_DocVsDepPosts"], "", "", (int)row["id"], id, id_status, false, false, 0); task.Wait(); } isEditData = false; MessageBox.Show("Данные сохранены.", "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; }
private bool AddSignAndConvertToPDF(typeFile tFile, FileData fData) { string FileName = fData.FileName; FileInfo newFile = new FileInfo(FileName); string FileNameToSaveAndSign = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; string FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + newFile.Extension; File.Copy(FileName, FileNameToSaveAndSign, true); string filePDF = pathSignTmpPDF + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".pdf"; newFile = new FileInfo(FileNameToSaveAndSign); Logging.Comment($"Начало обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); if (tFile == typeFile.word) { using (var document = DocX.Load(FileNameToSaveAndSign)) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } Xceed.Document.NET.Image image = document.AddImage(StrImage); Picture picture = image.CreatePicture(); //picture.Rotation = 10; picture.SetPictureShape(BasicShapes.cube); //picture.Height = 115; //picture.Width = 931; //Table table = document.Tables[3]; //table.Rows[7].Remove(); //table.Rows[8].Remove(); //table.Rows[7].MergeCells(0, table.Rows[7].Cells.Count); //table.Rows[7].Cells[0].Paragraphs[0].AppendPicture(picture); Table table = document.Tables[5]; //table.Rows[7].Remove(); table.Rows[10].Remove(); table.Rows[10].MergeCells(0, table.Rows[10].Cells.Count); //table.Rows[10].Cells[0].Paragraphs[0].InsertText("test"); table.Rows[10].Cells[0].Paragraphs[0].AppendPicture(picture); document.Save(); } filePDF = cnvWordToPDF.ConvertData(FileNameToSaveAndSign); } else if (tFile == typeFile.excel) { if (newFile.Extension.Equals(".xls")) { object paramMissing = Type.Missing; string newFileName = newFile.DirectoryName + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".xlsx"; var app = new Microsoft.Office.Interop.Excel.Application(); app.Caption = System.Guid.NewGuid().ToString().ToUpper(); var wb = app.Workbooks.Open(FileName); wb.SaveAs(newFileName, FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook); wb.Close(false, paramMissing, paramMissing); app.Quit(); Config.EnsureProcessKilled(IntPtr.Zero, app.Caption); Marshal.ReleaseComObject(wb); Marshal.FinalReleaseComObject(wb); wb = null; Marshal.ReleaseComObject(app); Marshal.FinalReleaseComObject(app); app = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); File.Delete(FileNameToSaveAndSign); FileNameToSaveAndSign = newFileName; newFile = new FileInfo(FileNameToSaveAndSign); } if (newFile.Extension.Equals(".xlsx")) { string StrImage = GetImageAgreements(fData.id_Landlord); if (StrImage.Length == 0) { if (File.Exists(FileNameToSaveAndSign)) { File.Delete(FileNameToSaveAndSign); } string sError = $"{fData.nameLandLord}: Отсутствует файлы для подписи"; if (!lStringError.Contains(fData.nameLandLord.Trim())) { //lStringError.Add(fData.nameLandLord); lStringError.Add(fData.nameLandLord + "/" + fData.nameObject); } return(false); } ExcelPackage epp = new ExcelPackage(newFile); Bitmap image = new Bitmap(StrImage); OfficeOpenXml.Drawing.ExcelPicture excelImage = null; var worksheet = epp.Workbook.Worksheets[0]; int countRow = worksheet.Dimension.End.Row; int countColumns = worksheet.Dimension.End.Column; bool isStop = false; for (int i = countRow; i > 0; i--) { for (int j = 1; j < countColumns; j++) { object value = worksheet.Cells[i, j].Value; if (value != null) { //Console.WriteLine(value); if (value.ToString().ToLower().Equals("Руководитель".ToLower()) || value.ToString().ToLower().Equals("Предприниматель".ToLower())) { fData.positonInsertSign = i - 1; isStop = true; break; } } } if (isStop) { break; } } excelImage = worksheet.Drawings.AddPicture("image", image); // In .SetPosition, we are using 8th Column and 8th Row, with 0 Offset //var rowCnt = worksheet.Dimension.End.Row; //var colCnt = worksheet.Dimension.End.Column; //worksheet.SetValue(fData.positonInsertSign, 1, "test"); //excelImage.SetPosition(38, 0, 0, 0); excelImage.SetPosition(fData.positonInsertSign, 0, 0, 0); //set size of image, 100= width, 100= height //excelImage.SetSize(931, 115); epp.Save(); //epp.SaveAs() } filePDF = cnvXLSToPDF.ConvertData(FileNameToSaveAndSign); } File.Delete(FileNameToSaveAndSign); newFile = new FileInfo(filePDF); DataTable dtScan = Config.hCntMain.getScan(fData.idAgreement, -1); bool isoverwrite = false; int id_Scane = 0; if (dtScan != null && dtScan.Rows.Count > 0) { EnumerableRowCollection <DataRow> rowCollectScan = dtScan.AsEnumerable().Where(r => r.Field <string>("cName").Contains(Path.GetFileNameWithoutExtension(filePDF))).OrderBy(r => r.Field <int>("id")); if (rowCollectScan.Count() > 0) { DialogResult dlResult = DialogResult.Cancel; Config.DoOnUIThread(() => { dlResult = new MyMessageBox.MyMessageBox($"В каталоге арендатора уже существует файл с сохраняемым именем \r\n \"{Path.GetFileNameWithoutExtension(filePDF)}\"", "Сохранение PDF файла счёта", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string>(new string[] { "Перезаписать", "Создать копию", "Отмена" })) { Owner = this }.ShowDialog(); }, this); if (dlResult == DialogResult.Cancel) { if (File.Exists(filePDF)) { File.Delete(filePDF); } Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: файл счёта не сохранён. Операция прервана пользователем"); MessageBox.Show(Config.centralText("PDF файл счёта не сохранён.\nОперация прервана пользователем\n"), "Сохранение PDF файла счёта", MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } if (dlResult == DialogResult.Yes) { Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Перезапись"); isoverwrite = true; //id_Scane = (int)rowCollectScan.First()["id"]; } else if (dlResult == DialogResult.No) { string filePDFTmp = filePDF.Replace(Path.GetFileNameWithoutExtension(filePDF), Path.GetFileNameWithoutExtension(filePDF) + $"({rowCollectScan.Count()})"); File.Move(filePDF, filePDFTmp); Logging.Comment($"{Path.GetFileNameWithoutExtension(filePDF)}: Копирование: Новое наименование файла: {Path.GetFileNameWithoutExtension(filePDFTmp)}"); filePDF = filePDFTmp; } } } string ServerPath = $"{net.server}\\{fData.idAgreement}"; //if (id_Scane == 0) //{ DataTable dtResult = Config.hCntMain.setScan(fData.idAgreement, Path.GetFileNameWithoutExtension(filePDF), newFile.Extension, 11, fData.Date, ServerPath); if (dtResult != null && dtResult.Rows.Count > 0) { id_Scane = (int)dtResult.Rows[0]["id"]; net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); } //} //else //{ // net.CopyFile(fData.idAgreement.ToString(), filePDF, Path.GetFileNameWithoutExtension(filePDF) + newFile.Extension, isoverwrite); //} Config.hCntMain.SetAgreement1CForAgreement(fData.idAgreement, fData.Number, fData.Date, fData.Agreement, fData.TypePay, fData.isAdd, id_Scane, !isoverwrite); Logging.Comment($"Запись в БД:[idAgreement:{fData.idAgreement};Номер: {fData.Number};Дата: {fData.Date}; Agreement: {fData.Agreement}; Тип оплаты:{fData.TypePay}]"); File.Delete(filePDF); try { File.Move(FileName, FileAndParse); } catch (IOException ex) { newFile = new FileInfo(FileName); string[] listFileInDir = Directory.GetFiles(pathEndParse + "\\", Path.GetFileNameWithoutExtension(FileName) + "*"); if (listFileInDir.Count() > 0) { FileAndParse = pathEndParse + "\\" + Path.GetFileNameWithoutExtension(FileName) + $"({listFileInDir.Count()})" + newFile.Extension; } File.Move(FileName, FileAndParse); } Logging.Comment($"Завершение обработки файла: { Path.GetFileNameWithoutExtension(filePDF)}"); return(true); }
private void btDelete_Click(object sender, EventArgs e) { if (dgvData.CurrentRow != null && dgvData.CurrentRow.Index != -1 && dtData != null && dtData.DefaultView.Count != 0) { int id = (int)dtData.DefaultView[dgvData.CurrentRow.Index]["id"]; bool isActive = (bool)dtData.DefaultView[dgvData.CurrentRow.Index]["isActive"]; string cName = (string)dtData.DefaultView[dgvData.CurrentRow.Index]["cName"]; int npp = (int)dtData.DefaultView[dgvData.CurrentRow.Index]["npp"]; bool ViewAdd = (bool)dtData.DefaultView[dgvData.CurrentRow.Index]["ViewAdd"]; bool ViewArchive = (bool)dtData.DefaultView[dgvData.CurrentRow.Index]["ViewArchive"]; Task <DataTable> task = Config.hCntMain.setTypeDoc(id, cName, npp, ViewAdd, ViewArchive, isActive, true, 0); task.Wait(); if (task.Result == null) { MessageBox.Show(Config.centralText("При сохранение данных возникли ошибки записи.\nОбратитесь в ОЭЭС\n"), "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int result = (int)task.Result.Rows[0]["id"]; if (result == -1) { MessageBox.Show(Config.centralText("Запись уже удалена другим пользователем\n"), "Удаление записи", MessageBoxButtons.OK, MessageBoxIcon.Information); get_data(); return; } if (result == -2 && isActive) { DialogResult dlgResult = new MyMessageBox.MyMessageBox("В программе присутствуют документы\n с удаляемым типом.\nВы хотите перевести документы\n в статус \"Архив\"?", "Удаление типа документа", MyMessageBox.MessageBoxButtons.YesNoCancel, new List <string> { "Да, в архив", "Нет, не в архив", "Отмена" }).ShowDialog(); if (dlgResult == DialogResult.Cancel) { return; } if (dlgResult == DialogResult.Yes) { if (DialogResult.OK == new justification.frmAdd() { id_TypeDoc = id }.ShowDialog()) { setLog(id, 3); task = Config.hCntMain.setTypeDoc(id, cName, npp, ViewAdd, ViewArchive, !isActive, false, 0); task.Wait(); if (task.Result == null) { MessageBox.Show(Config.centralText("При сохранение данных возникли ошибки записи.\nОбратитесь в ОЭЭС\n"), "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } get_data(); return; } else //if (DialogResult.Yes == MessageBox.Show(Config.centralText("Выбранная для удаления запись используется в программе.\nСделать запись недействующей?\n"), "Удаление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { setLog(id, 3); task = Config.hCntMain.setTypeDoc(id, cName, npp, ViewAdd, ViewArchive, !isActive, false, 0); task.Wait(); if (task.Result == null) { MessageBox.Show(Config.centralText("При сохранение данных возникли ошибки записи.\nОбратитесь в ОЭЭС\n"), "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } get_data(); return; } } } else if (result == 0 && isActive) { if (DialogResult.Yes == MessageBox.Show("Удалить выбранную запись?", "Удаление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { setLog(id, 2); task = Config.hCntMain.setTypeDoc(id, cName, npp, ViewAdd, ViewArchive, isActive, true, 1); task.Wait(); if (task.Result == null) { MessageBox.Show(Config.centralText("При сохранение данных возникли ошибки записи.\nОбратитесь в ОЭЭС\n"), "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } get_data(); return; } } else if (!isActive) { if (DialogResult.Yes == MessageBox.Show("Сделать выбранную запись действующей?", "Восстановление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { setLog(id, 4); task = Config.hCntMain.setTypeDoc(id, cName, npp, ViewAdd, ViewArchive, !isActive, false, 0); task.Wait(); if (task.Result == null) { MessageBox.Show(Config.centralText("При сохранение данных возникли ошибки записи.\nОбратитесь в ОЭЭС\n"), "Сохранение данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } get_data(); return; } } } }