ExportControl.cs
Description du code
ExportControl.cs est un fichier du projet BiblioBrol.Ce fichier est situé dans /var/www/bin/sniplets/bibliobrol/src/.
Projet BiblioBrol :
Gestion de media en CSharp.
Pour plus d'infos, vous pouvez consulter la brève analyse.
Code source ou contenu du fichier
Code c# (ExportControl.cs) (653 lignes)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using be.gaudry.bibliobrol.model; using System.Threading; using be.gaudry.bibliobrol.view.dialogs; using be.gaudry.observer; using be.gaudry.bibliobrol.config; namespace be.gaudry.bibliobrol.view.utils { internal delegate void ChangeTextDelegateHandler(Control control, String text); internal delegate void AppendTextDelegateHandler(RichTextBox rtb, String text); internal delegate void SetProgressBarDelegateHandler(ProgressBar pgb, int value); internal delegate void IncreaseProgressBarDelegateHandler(ProgressBar pgb, int value); internal delegate void ThreadHasFinishDelegateHandler(); public partial class ExportControl : UserControl, IObserver { #region Constructors and declarations /// <summary> /// MediaBrols ids or Brols ids to export /// </summary> private List<int> ids; private ChangeTextDelegateHandler ChangeTextDelegate; private AppendTextDelegateHandler AppendTextDelegate; private SetProgressBarDelegateHandler SetProgressBarDelegate; private IncreaseProgressBarDelegateHandler IncreaseProgressBarDelegate; private ThreadHasFinishDelegateHandler ThreadHasFinishedDelegate; private Thread exportationThread; /// <summary> /// Form containing this user control. /// We use it to add delegate on close form event, and to get selected ids to export /// </summary> private MediabrolForm f; /// <summary> /// Used to set button text /// </summary> private String showDetails, hideDetails; /// <summary> /// Used to store data needed by update method /// </summary> private IAsyncResult ia, ia2; /// <summary> /// Used to read fileName from another thread /// </summary> String exportFileName; /// <summary> /// Constructor /// </summary> public ExportControl() { InitializeComponent(); initControls(); initProgressBar(); } #endregion #region initializations private void initControls() { exportViewRTB.Text = String.Empty; exportExtCB.SelectedIndex = 0; fillExportName(); progressGB.Visible = false; exportViewRTB.Visible = false; showDetails = "Afficher les détails"; hideDetails = "Masquer les détails"; } private void initProgressBar() { this.threadPriorityCB.SelectedIndex = 2; this.threadPriorityCB.SelectedIndexChanged += new EventHandler(threadPriorityCB_SelectedIndexChanged); } #endregion #region public methods /// <summary> /// Set the form from which we need to read datagridview values /// Add event to abort threads which may be still alive on BIblioItemForm closing /// </summary> /// <param name="f">BIblioItemForm</param> public void setBIblioItemForm(MediabrolForm f) { this.f = f; } #endregion #region manage file name /// <summary> /// Used to init fields values. /// fill path textbox with application directory path /// fill filename with preformated name (with date) /// </summary> private void fillExportName() { dirPathTB.Text = Config.ExportDir; DateTime dt = DateTime.Now; str.Append(dt.Year); if (dt.Month < 10) str.Append("0"); str.Append(dt.Month); if (dt.Day < 10) str.Append("0"); str.Append(dt.Day); fileNameTB.Text = str.ToString(); } /// <summary> /// Set full name with directory path, filename, and extension /// </summary> /// <returns></returns> private void setExportName() { str.Append(System.IO.Path.DirectorySeparatorChar); str.Append(fileNameTB.Text); str.Append("."); switch (exportExtCB.SelectedIndex) { case 0: str.Append("bed"); break; case 3: str.Append("xls"); break; default: str.Append(((String)exportExtCB.SelectedItem).ToLower()); break; } exportFileName = str.ToString(); } /// <summary> /// Allow to browse to get directory path and fill textbox with it /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void browseDirBtn_Click(object sender, EventArgs e) { fbDia.Description = "Dossier des fichiers à exporter ou importer"; //fbDia.RootFolder = Application.StartupPath; fbDia.ShowNewFolderButton = true; fbDia.SelectedPath = Config.ExportDir; //Application.StartupPath; if (fbDia.ShowDialog(this) == DialogResult.OK) { dirPathTB.Text = fbDia.SelectedPath; } else { dirPathTB.Text = ""; } } private bool testFileName(String fileName) { if (!System.IO.Directory.Exists(dirPathTB.Text)) { StaticObservable.notify(new Notification(Notification.VERBOSE.opsResult, "Exportation", String.Format("Le chemin {0} n'est pas valide.", fileName), this)); return false; } return true; } #endregion #region export / import /// <summary> /// Abort thread which is doing the exportation /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cancelExportBtn_Click(object sender, EventArgs e) { Invoke(ThreadHasFinishedDelegate); exportClosing(null,null); appendText(exportViewRTB, "Opération annulée"); } /// <summary> /// Export data with selected parameters /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportBtn_Click(object sender, EventArgs e) { setExportName(); if (!testFileName(exportFileName)) return; /*foreach (DataRow row in f.dataTable.Rows) { ids.Add((int)row["mbId"]); }*/ //int nbExp = f.dataTable.Rows.Count; int nbExp = f.MediabrolIds.Count; if (nbExp < 1) { StaticObservable.notify(new Notification(Notification.VERBOSE.opsResult, "Exportation", "Aucun élément à exporter", this)); return; } DialogResult r = MessageBox.Show( this, "Exporter les " + nbExp + " éléments sélectionnés vers \n" + exportFileName, "Exportation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (r == DialogResult.OK) { switch(exportExtCB.SelectedIndex) { #region binary export case 0: showProgression(); switch (testPerformsCB.SelectedIndex) { case 1 : //notifications and single thread ModelAdapter.addImportExporterObserver(this); ModelAdapter.removeImportExporterObserver(this); break; case 2: //no notifications and separated thread this.exportationThread.Name = "ExportThread"; this.exportationThread.Priority = ThreadPriority.Normal; this.exportationThread.Start(); break; case 3: //no notifications and single thread ModelAdapter.addImportExporterObserver(this); ModelAdapter.removeImportExporterObserver(this); break; default: //notifications and separated thread this.exportationThread.Name = "ExportThread"; this.exportationThread.Priority = ThreadPriority.Normal; this.exportationThread.Start(); break; } break; #endregion //binary export #region xml export case 1 : ModelAdapter.addImportExporterObserver(this); ModelAdapter.exportXMLMediaBrol(ids.ToArray(), exportFileName); ModelAdapter.removeImportExporterObserver(this); break; #endregion #region csv export case 2: ModelAdapter.addImportExporterObserver(this); ModelAdapter.exportExcelMediaBrol(ids.ToArray(), exportFileName,1); ModelAdapter.removeImportExporterObserver(this); break; #endregion #region MS Excel export case 3: ModelAdapter.addImportExporterObserver(this); ModelAdapter.exportExcelMediaBrol(ids.ToArray(), exportFileName,2); ModelAdapter.removeImportExporterObserver(this); break; #endregion #region default default : break; #endregion } } } /// <summary> /// Set stepControls to show the progression /// </summary> private void showProgression() { progressGB.Visible = true; exportViewRTB.Text = String.Empty; exportViewRTB.Visible = false; cancelExportBtn.Visible = true; exportBtn.Visible = false; } /// <summary> /// Used to call export method, with parameters, in a thread throught a delegate. /// Call the same method as executeExport(), but without notifications (to test performances) /// </summary> public void executeTest() { ModelAdapter.addImportExporterObserver(this); } /// <summary> /// Used to call export method, with parameters, in a thread throught a delegate /// </summary> public void executeExport() { ModelAdapter.addImportExporterObserver(this); } /// <summary> /// Used to call export method, with parameters, in a thread throught a delegate /// </summary> public void executeImport() { ModelAdapter.addImportExporterObserver(this); ModelAdapter.importBinaryMediaBrol(exportFileName); } /// <summary> /// Fill a RichTextBox with exported file content /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fetchDataBtn_Click(object sender, EventArgs e) { setExportName(); if (!testFileName(exportFileName)) return; exportViewRTB.Visible = true; exportViewRTB.Text = string.Empty; exportViewRTB.Visible = true; System.IO.StreamReader sr = null; try { string data = sr.ReadLine(); while (data != null) { exportViewRTB.AppendText(data + "\r\n"); data = sr.ReadLine(); } } catch (System.IO.IOException ioe) { StaticObservable.notify(new Notification(Notification.VERBOSE.lowError, "Exportation", "Erreur de lecture du fichier exporté", ioe, this)); exportViewRTB.Visible = false; } finally { if (sr != null)sr.Close(); } } /// <summary> /// Fetch titles into and send ops result as notification /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void importBtn_Click(object sender, EventArgs e) { setExportName(); if (!testFileName(exportFileName)) return; if (((String)exportExtCB.SelectedItem).Equals("Binaire")) { /*ModelAdapter.addImportExporterObserver(this); ModelAdapter.importBinaryMediaBrol(exportFileName); ModelAdapter.removeImportExporterObserver(this);*/ showProgression(); this.exportationThread.Name = "ExportThread"; this.exportationThread.Priority = ThreadPriority.Normal; this.exportationThread.Start(); } else { StaticObservable.notify(new Notification(Notification.VERBOSE.opsResult, "Exportation", "Fonctionnalité en cours d'élaboration pour " + (String)exportExtCB.SelectedItem, this)); } } #endregion #region progress bars /// <summary> /// Abort exportationThread if needed /// </summary> private void exportClosing(object sender, FormClosingEventArgs e) { // If the thread is still alive if (this.exportationThread != null && this.exportationThread.IsAlive) { this.exportationThread.Abort(); this.exportationThread = null; } } /// <summary> /// Increase progress bar /// </summary> /// <param name="pgb">increaseProgressBar to increase</param> /// <param name="value">(int) Value of increase</param> private void increaseProgressBar(ProgressBar pgb, int value) { pgb.Increment(value); } /// <summary> /// Set max value of progress bar /// </summary> /// <param name="pgb">increaseProgressBar to set max value</param> /// <param name="value">(int) max value</param> private void setProgressBar(ProgressBar pgb, int value) { pgb.Maximum = value; pgb.Value = 0; } /// <summary> /// Called when the thread has finish /// </summary> private void threadHasFinish() { ModelAdapter.removeImportExporterObserver(this); progressGB.Visible = false; exportViewRTB.Visible = true; cancelExportBtn.Visible = false; exportBtn.Visible = true; } /// <summary> /// Modify text of a Control /// </summary> /// <param name="control">Control which we need to modify text</param> /// <param name="text">(String) text to modify</param> private void changeText(Control control, String text) { control.Text = text; } /// <summary> /// Append text for a RichTextBox /// </summary> /// <param name="rtb">RichTextBox which we need to append text</param> /// <param name="text">(String) text to modify</param> private void appendText(RichTextBox rtb, String text) { rtb.AppendText("\n"); rtb.AppendText(text); rtb.ScrollToCaret(); } /// <summary> /// Modify Thread priority /// </summary> private void threadPriorityCB_SelectedIndexChanged(object sender, EventArgs e) { if (this.exportationThread != null) { switch (this.threadPriorityCB.SelectedIndex) { case 0: this.exportationThread.Priority = ThreadPriority.Highest; break; case 1: this.exportationThread.Priority = ThreadPriority.AboveNormal; break; case 2: this.exportationThread.Priority = ThreadPriority.Normal; break; case 3: this.exportationThread.Priority = ThreadPriority.BelowNormal; break; case 4: this.exportationThread.Priority = ThreadPriority.Lowest; break; default: this.exportationThread.Priority = ThreadPriority.Normal; break; } } } #endregion #region IObserver Members /// <summary> /// Call needed functions to use progress bars and display infos /// </summary> /// <param name="n">(Notification) Notified infos</param> public void update(Notification n) { int bCount, bCount2; switch(n.Level) { case Notification.VERBOSE.internalNotification : try { switch (n.Title) { case "count": Int32.TryParse(n.Msg, out bCount); // set main progress bax max value this.Invoke(SetProgressBarDelegate, this.pgbTotal, bCount); break; case "brolStart": if (showHideDetailsBtn.Text.Equals(hideDetails)) { // modify current asynchronous (non bloquant) mediabrol loading ia = this.BeginInvoke(ChangeTextDelegate, this.lblCurrentFile, n.Msg); } break; case "brolEnd": // asynchronous increase of main progress bar ia2 = this.BeginInvoke(IncreaseProgressBarDelegate, this.pgbTotal, 1); if (showHideDetailsBtn.Text.Equals(hideDetails)) { this.EndInvoke(ia); } this.EndInvoke(ia2); break; case "pb2": //increase details progress bar if (showHideDetailsBtn.Text.Equals(hideDetails)) { this.Invoke(IncreaseProgressBarDelegate, this.pgbCurrent, 1); } break; case "Info": this.Invoke(ChangeTextDelegate, this.lblCurrentFile, n.Msg); break; case "End": this.Invoke(ThreadHasFinishedDelegate); this.Invoke(AppendTextDelegate, this.exportViewRTB, n.Msg); break; case "count2": if (showHideDetailsBtn.Text.Equals(hideDetails)) { Int32.TryParse(n.Msg, out bCount2); this.Invoke(SetProgressBarDelegate, this.pgbCurrent, bCount2); } break; default: //modify general info label this.Invoke(AppendTextDelegate, this.exportViewRTB, n.Msg); break; } } catch (ThreadAbortException) { //this.Invoke(ThreadHasFinishedDelegate); } break; /* No need if we add console as importExporter observer case Notification.VERBOSE.criticalError: System.Console.WriteLine(n.Title + " : " + n.Msg); StaticObservable.notify(n); break; case Notification.VERBOSE.opsResult: System.Console.WriteLine(n.Title + " : " + n.Msg); StaticObservable.notify(n); break; */ } } #endregion #region private methods /// <summary> /// If we don't export mediabrols, anonymous has no sense with only brols. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void expMediabrolChkB_CheckedChanged(object sender, EventArgs e) { { anonymousChkB.Enabled = true; } else { anonymousChkB.Enabled = false; } } /// <summary> /// Show or hide progress details panel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void showHideDetailsBtn_Click(object sender, EventArgs e) { showHideDetailsBtn.Text = (!progressDetailsPanel.Visible) ? hideDetails : showDetails; progressDetailsPanel.Visible = !progressDetailsPanel.Visible; } #endregion #region help /// <summary> /// Display MessageBox with info about export mediabrol option /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void expMediabrolInfoBtn_Click(object sender, EventArgs e) { str.AppendLine("Si cette case est cochée, les exemplaires des ouvrages sont exportés (sans les emprunts)."); str.AppendLine("Sinon, seuls les informations relatives aux ouvrages sont sélectionnés."); MessageBox.Show( str.ToString(), "Info bibliobrol", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } /// <summary> /// Display MessageBox with info about export all brols option /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void expAllBrolInfoBtn_Click(object sender, EventArgs e) { str.AppendLine("Si cette case est cochée, tous les ouvrages existants seront exportés."); str.AppendLine("Sinon, seuls les ouvrages dont les exemplaires sont sélectionnés seront exportés."); MessageBox.Show( str.ToString(), "Info bibliobrol", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } /// <summary> /// Display MessageBox with info about anonymous option /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void anonymousInfoBtn_Click(object sender, EventArgs e) { str.AppendLine("Si cette case est cochée, le nom du propriétaire ne sera pas exporté pour les exemplaires."); MessageBox.Show( str.ToString(), "Info bibliobrol", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } #endregion private void testImgsBtn_Click(object sender, EventArgs e) { iif.ShowDialog(this); } } }
Structure et Fichiers du projet
Afficher/masquer...Icône | Nom | Taille | Modification |
Pas de sous-répertoires. | |||
Icône | Nom | Taille | Modification |
| _ | Répertoire parent | 0 octets | 1731646773 15/11/2024 05:59:33 |
Utilisation de l'explorateur de code
- Navigation :
- Un clic sur une icône de répertoire ouvre ce répertoire pour en afficher les fichiers.
- Lorsque le répertoire en cours ne contient pas de sous-répertoires il est possible de remonter vers le répertoire parent.
- La structure de répertoires en treetable (tableau en forme d'arborescence) n'est plus possibledans cette version.
- Un clic sur une icône de fichier ouvre ce fichier pour en afficher le code avec la coloration syntaxique adaptée en fonction du langage principal utilisé dans le fichier.
- Affichage :
- Il est possible de trier les répertoires ou les fichiers selon certains critères (nom, taille, date).
- Actions :
- Les actions possible sur les fichiers dépendent de vos droits d'utilisateur sur le site. Veuillez activer le mode utilisateur pour activer les actions.
English translation
You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.
Thank you in advance.
Document created the 16/10/2009, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/cs-bibliobrol-source-rf-view/utils//ExportControl.cs.html
The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.