AccessExporterDao.cs
Description du code
AccessExporterDao.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# (AccessExporterDao.cs) (725 lignes)
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data.Common; using System.Data; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Drawing; using be.gaudry.observer; using be.gaudry.model.enums; using be.gaudry.model; using be.gaudry.model.exceptions; namespace be.gaudry.bibliobrol.model.dao.msaccess { public sealed class AccessExporterDao : Observable, IExporterDao { private String conStr; private enum MBCOMPAR { existingItem, newItem, conflictItem }; #region singleton static AccessExporterDao instance = null; private DbProviderFactory dbpf; AccessExporterDao() { dbpf = ((AccessFactory)AccessFactory.Instance).getDbpf(); conStr = ((AccessFactory)AccessFactory.Instance).getConnectionString(); } public static AccessExporterDao Instance { get { lock (padlock) { if (instance == null) { } return instance; } } } #endregion #region private methods /// <summary> /// Used to decorate FileStream constructor. /// Add exceptions catching and notifications on errors. /// </summary> /// <param name="path">(String) Path of the file</param> /// <param name="fMode">FileMode</param> /// <param name="fAccess">FileAccess</param> /// <returns>new FileStream or null</returns> internal FileStream getFileStream(String path, FileMode fMode, FileAccess fAccess) { String internEx = null; try { return fs; } catch (System.IO.IOException ioe) { internEx = ioe.Message; notify(new Notification(Notification.VERBOSE.criticalError, "Importation", "Erreur avec le fichier à importer", ioe, this)); } catch (System.Security.SecurityException sex) { internEx = sex.Message; notify(new Notification(Notification.VERBOSE.criticalError, "Importation", "Erreur de sécurité avec le fichier d'importation", sex, this)); } catch (System.UnauthorizedAccessException uae) { internEx = uae.Message; notify(new Notification(Notification.VERBOSE.criticalError, "Importation", "Accès non autorisé", uae, this)); } catch (Exception fSer) { internEx = fSer.Message; } //internalNotification to send msg to the import/export observer return null; } #endregion #region binary /// <summary> /// Serialize itemms list of Brols or Mediabrols /// </summary> /// <param name="mediabrolIds">(int[]) array of mediabrol's ids</param> /// <param name="path">(String) path of binary export file</param> /// <param name="exportMediabrol">(bool) true if mediabrols must be exported, false if only brols must be exported</param> /// <param name="exportAllBrols">(bool) true if non selected brols must be also exported</param> /// <param name="anonymous">(bool) true if owner info may not be exported</param> public void exportBinaryMediaBrol(int[] ids, String path, bool exportMediabrol, bool exportAllBrols, bool anonymous) { "exportMediabrol : "+exportMediabrol+" "+ "\nexportAllBrols : "+exportAllBrols+" "+ "\nanonymous : "+anonymous, this)); if (ids == null) { notify(new Notification(Notification.VERBOSE.opsResult, "Exportation", "Aucun élément à exporter", this)); return; } if (path == null) { notify(new Notification(Notification.VERBOSE.criticalError, "Exportation", "Aucun chemin sélectionné pour exporter", this)); return; } DateTime startDateTime = DateTime.Now; List<Brol> brols = null; List<MediaBrol> mediabrols = null; DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbDa.SelectCommand = dbCon.CreateCommand(); dbCon.ConnectionString = conStr; if (exportMediabrol) { mediabrols = loadSelectedMediaBrols(ids, anonymous, dbCon, dbDa); } else { brols = loadSelectedBrols(ids, dbCon, dbDa, true); Image img = null; foreach (Brol brol in brols) { try { img = Image.FromFile(be.gaudry.bibliobrol.view.utils.Img.getBrolImgPath(brol)); images.Add(img); } catch (Exception) { } } } dbCon.Close(); FileStream fs = getFileStream(path, FileMode.OpenOrCreate, FileAccess.Write); if(fs==null) { notify(new Notification(Notification.VERBOSE.internalNotification, "End", "Impossible de terminer le traitement", this)); return; } try { notify(new Notification(Notification.VERBOSE.internalNotification, "Info", "Début de la sauvegarde", this)); if (exportMediabrol) bf.Serialize(fs, mediabrols); else { bf.Serialize(fs, brols); fs.Close(); fs = getFileStream(path.Replace(".bed",".bif"), FileMode.OpenOrCreate, FileAccess.Write); bf.Serialize(fs, images); } notify(new Notification(Notification.VERBOSE.internalNotification, "Info", "Fin de la sauvegarde", this)); } catch (Exception eSer) { notify(new Notification(Notification.VERBOSE.internalNotification, "End", "Impossible de terminer le traitement : " + eSer.Message, this)); return; } finally { fs.Close(); } //exportImgs(exportMediabrol, ibrols); notify(new Notification(Notification.VERBOSE.internalNotification, "End", String.Format("Fin de tous les traitements ({0})", Units.getDelay(startDateTime)), this)); } /*private void exportImgs(bool exportMediabrol, List<IBrol> ibrols) { List<Brol> brols = new List<Brol>(); if (exportMediabrol) { } else { } } private void exportBrolImgs(List<Brol> brols) { }*/ /// <summary> /// Serialize mediabrols /// </summary> /// <param name="mediabrolIds">(int[]) array of mediabrol's ids</param> /// <param name="path">(String) path of binary export file</param> /// <param name="exportMediabrol">(bool) true if mediabrols must be exported, false if only brols must be exported</param> /// <param name="exportAllBrols">(bool) true if non selected brols must be also exported</param> /// <param name="anonymous">(bool) true if owner info may not be exported</param> public void exportBinaryMediaBrolTest(int[] mediabrolIds, String path, bool exportMediabrol, bool exportAllBrols, bool anonymous) { DateTime startDateTime = DateTime.Now; if (mediabrolIds == null)return; if (path == null)return; DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbDa.SelectCommand = dbCon.CreateCommand(); dbCon.ConnectionString = conStr; str.Append("(itemBiblio AS i"); str.Append(" LEFT JOIN person AS p ON i.ownerId = p.id)"); str.Append(" LEFT JOIN media AS m ON i.mediaId = m.id"); str.Append(" WHERE i.id IN (0"); foreach (int id in mediabrolIds) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); MediaBrol mediabrol; try { dbDa.Fill(brolDt); int mbCount = brolDt.Rows.Count; int brolId; foreach (DataRow brolRow in brolDt.Rows) { mediabrol = msaccess.AccessMediaBrolDao.Instance.getMediaBrol(brolRow, anonymous); try { brolId = (int)brolRow["itemId"]; mediabrol.Brol = AccessBrolDao.Instance.loadBrol(brolId, false); } catch (Exception){} try { mediabrol.Qualities = msaccess.AccessMediaBrolDao.Instance.loadQualitiesCommand(mediabrol.Id, dbDa); mediabrols.Add(mediabrol); } catch (Exception){} } } catch (Exception){} finally { brolDt.Dispose(); dbCon.Close(); } FileStream fs = getFileStream(path, FileMode.OpenOrCreate, FileAccess.Write); if (fs == null) return; try { bf.Serialize(fs, mediabrols); } catch (Exception){} fs.Close(); notify(new Notification(Notification.VERBOSE.internalNotification, "End", String.Format("Fin de tous les traitements ({0})", Units.getDelay(startDateTime)), this)); } #endregion #region xml /// <summary> /// Export mediabrols into xml file /// </summary> /// <param name="mediabrolIds">(int[]) array of mediabrol's ids</param> /// <param name="path">(String) path of xml export file</param> public void exportXMLMediaBrol(int[] mediabrolIds, String path) { if (mediabrolIds == null) { notify(new Notification(Notification.VERBOSE.opsResult, "Exportation des exemplaires", "Aucun exemplaire à exporter", this)); return; } if (path == null) { notify(new Notification(Notification.VERBOSE.criticalError, "Exportation des exemplaires", "Aucun chemin sélectionné pour exporter", this)); return; } DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbDa.SelectCommand = dbCon.CreateCommand(); dbCon.ConnectionString = conStr; str.Append("(itemBiblio AS i"); str.Append(" LEFT JOIN person AS p ON i.ownerId = p.id)"); str.Append(" LEFT JOIN media AS m ON i.mediaId = m.id"); str.Append(" WHERE i.id IN (0"); foreach (int id in mediabrolIds) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); try { dbDa.Fill(ds); ds.WriteXml(path); notify(new Notification(Notification.VERBOSE.opsResult, "Exportation des données", "Les données ont bien été exportées dans le fichier " + path, this)); } catch (Exception e) { notify(new Notification(Notification.VERBOSE.criticalError, "Impossible d'exporter les données", e, this)); } finally { ds.Dispose(); dbCon.Close(); } } #endregion #region MS Excel /// <summary> /// Export mediabrols into CSV or MS Excel Stylesheet file /// </summary> /// <param name="mediabrolIds">(int[]) array of mediabrol's ids</param> /// <param name="path">(String) path of the export file</param> /// <param name="type">(int) type of export (CSV or MS Excel)</param> public void exportExcelMediaBrol(int[] mediabrolIds, String path, int type) { if (mediabrolIds == null) { notify(new Notification(Notification.VERBOSE.opsResult, "Exportation des exemplaires", "Aucun exemplaire à exporter", this)); return; } if (path == null) { notify(new Notification(Notification.VERBOSE.criticalError, "Exportation des exemplaires", "Aucun chemin sélectionné pour exporter", this)); return; } { //"n°", //0 "nom d'exemplaire", //1 "n° d'ouvrage", //2 //"n° de propriétaire", //3 //"n° de support", //4 "Date d'insertion", //5 "Commentaire", //6 "Localisation", //7 //"n° de propriétaire", //8 "Nom de propriétaire", //9 "Prénom de propriétaire", //10 //"Date de naissance proprio",//11 //"Sexe proprio", //12 //"Verrou proprio", //13 //"Pseudonyme propriétaire", //14 //"n° de support", //15 "Support", //16 "Type d'ouvrage" //17 }; DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbDa.SelectCommand = dbCon.CreateCommand(); dbCon.ConnectionString = conStr; str.Append("(itemBiblio AS i"); str.Append(" LEFT JOIN person AS p ON i.ownerId = p.id)"); str.Append(" LEFT JOIN media AS m ON i.mediaId = m.id"); str.Append(" WHERE i.id IN (0"); foreach (int id in mediabrolIds) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); try { dbDa.Fill(dt); if (type == 1) exportCSV(dt, path, headers, cols); else exportExcel(dt, path, headers, cols); notify(new Notification(Notification.VERBOSE.opsResult, "Exportation des données", "Les données ont bien été exportées dans le fichier " + path, this)); } catch (Exception e) { notify(new Notification(Notification.VERBOSE.criticalError, "Impossible d'exporter les données", e, this)); } finally { dt.Dispose(); dbCon.Close(); } } private void exportExcel(DataTable dt, String path, string[] headers, int[] cols) { // Export all the details try { // Export the details of specified columns to CSV objExport.ExportDetails(dt, cols, headers, BROL_EXPORT_FORMAT.Excel, path); } catch (Exception e) { notify(new Notification(Notification.VERBOSE.criticalError, "Impossible d'exporter les données", e, this)); } } private void exportCSV(DataTable dt, String path, string[] headers, int[] cols) { // Export all the details try { // Specify the column list to export /*int c = dt.Columns.Count-1; int[] iColumns = new int[c]; for (int i = 0; i <= c; i++) { iColumns[i] = i; } */ // Export the details of specified columns to CSV objExport.ExportDetails(dt, cols, headers, BROL_EXPORT_FORMAT.CSV, path); } catch (Exception e) { notify(new Notification(Notification.VERBOSE.criticalError, "Impossible d'exporter les données", e, this)); } } #endregion #region load brols and mediabrols /// <summary> /// Load a list with selected mediabrols with an existing connection. /// </summary> /// <param name="ids">(int[]) mediabrols identifiers</param> /// <param name="dbCon">DbConnection</param> /// <param name="dbDa">DbDataAdapter</param> /// <returns>List of mediabrols</returns> private List<MediaBrol> loadSelectedMediaBrols(int[] ids, bool anonymous, DbConnection dbCon, DbDataAdapter dbDa) { str.Append("(itemBiblio AS i"); str.Append(" LEFT JOIN person AS p ON i.ownerId = p.id)"); str.Append(" LEFT JOIN media AS m ON i.mediaId = m.id"); str.Append(" WHERE i.id IN (0"); foreach (int id in ids) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); MediaBrol mediabrol; try { dbDa.Fill(brolDt); int mbCur = 0; int mbCount = brolDt.Rows.Count; notify(new Notification(Notification.VERBOSE.internalNotification, "count", mbCount.ToString(), this)); notify(new Notification(Notification.VERBOSE.internalNotification, "Chargement des ouvrages", String.Format("{0} exemplaires chargés(s) sur {0} demandé(s)", mbCount, ids.Length), this)); foreach (DataRow brolRow in brolDt.Rows) { mediabrol = msaccess.AccessMediaBrolDao.Instance.getMediaBrol(brolRow, anonymous); try { brolIds[0] = (int)brolRow["itemId"]; //mediabrol.Brol = AccessBrolDao.Instance.loadBrol(brolId, false); mediabrol.Brol = (loadSelectedBrols(brolIds, dbCon, dbDa, false))[0]; notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", String.Format("Chargement de l'ouvrage {0}/{1} : {2}", ++mbCur, mbCount, mediabrol.Brol.Title), this)); } catch (Exception eBrol) { } try { mediabrol.Qualities = msaccess.AccessMediaBrolDao.Instance.loadQualitiesCommand(mediabrol.Id, dbDa); mediabrols.Add(mediabrol); } catch (Exception eBrol) { } finally { } } notify(new Notification(Notification.VERBOSE.internalNotification, "lastBrol", String.Format("Fin des {0} chargements", mbCount), this)); } catch (Exception eMedia) { notify(new Notification(Notification.VERBOSE.advancedOperation, "Chargement des ouvrages", eMedia, this)); } finally { brolDt.Dispose(); } return mediabrols; } /// <summary> /// Load a list with selected brols /// </summary> /// <param name="ids">(int[]) brol identifiers</param> /// <returns>List of Brols</returns> internal List<Brol> loadSelectedBrols(int[] ids) { if (ids.Length < 1) { notify(new Notification(Notification.VERBOSE.lowError, "Chargement des ouvrages", "Aucun ouvrage à charger", this)); } DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); List<Brol> brols = loadSelectedBrols(ids, dbCon, dbDa, false); dbCon.Close(); return brols; } /// <summary> /// Load a list with selected brols with an existing connection. /// </summary> /// <param name="ids">(int[]) brol identifiers</param> /// <param name="dbCon">DbConnection</param> /// <param name="dbDa">DbDataAdapter</param> /// <param name="internalNotification">(bool) True if we use a progress bar</param> /// <returns>List of Brols</returns> internal List<Brol> loadSelectedBrols(int[] ids, DbConnection dbCon, DbDataAdapter dbDa, bool internalNotification) { dbDa.SelectCommand = dbCon.CreateCommand(); dbCon.ConnectionString = conStr; //build brols datatable str.Append(" RIGHT JOIN item ON type.id = item.typeId"); str.Append(" WHERE item.id IN (0"); foreach (int id in ids) { str.Append(","); str.Append(id); idslist.Add(id); } idslist.Sort(); str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); try { dbDa.Fill(ds, "brolsDT"); int mbCur = 0; int mbCount = ds.Tables["brolsDT"].Rows.Count;//ids.Length; if (internalNotification) { notify(new Notification(Notification.VERBOSE.internalNotification, "count", (mbCount+1).ToString(), this)); notify(new Notification(Notification.VERBOSE.internalNotification, "Chargement des ouvrages", String.Format("{0} ouvrages chargé(s) sur {0} demandé(s)", mbCount, ids.Length), this)); notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", "Chargement des catégories", this)); } //load categories str.Append(" LEFT JOIN categoryItemRelation ON categoryItemRelation.categoryId = category.id"); str.Append(" WHERE itemId IN (0"); foreach (int id in ids) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); dbDa.Fill(ds, "categoriesDT"); //build relation "media-catégorie", ds.Tables["brolsDT"].Columns["id"], ds.Tables["categoriesDT"].Columns["itemId"] ); AccessBrolDao.Instance.tryToAddRelation(ds, dr); if (internalNotification) { notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", "Chargement des acteurs", this)); } //load serie str.Append(" LEFT JOIN serieItemRelation ON serieItemRelation.serieId = serie.id"); str.Append(" WHERE itemId IN (0"); foreach (int id in ids) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); dbDa.Fill(ds, "seriesDT"); //build relation "media-serie", ds.Tables["brolsDT"].Columns["id"], ds.Tables["seriesDT"].Columns["itemId"] ); AccessBrolDao.Instance.tryToAddRelation(ds, drSerie); /*if (internalNotification) { notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 2", this)); notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", "Chargement des acteurs", this)); } */ //load actors str.Append(" FROM role RIGHT JOIN"); str.Append(" (person AS p INNER JOIN actor AS a ON p.id=a.personId)"); str.Append(" ON role.id=a.roleId"); str.Append(" WHERE a.itemId IN (0"); foreach (int id in ids) { str.Append(","); str.Append(id); } str.Append(")"); dbDa.SelectCommand.CommandText = str.ToString(); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); if (internalNotification) { notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", "Chargement des acteurs", this)); } try { dbDa.Fill(ds, "actorsDT"); //build relation "media-personnes", ds.Tables["brolsDT"].Columns["id"], ds.Tables["actorsDT"].Columns["itemId"] ); AccessBrolDao.Instance.tryToAddRelation(ds, drActors); //build person objects foreach (DataRow brolRow in ds.Tables["brolsDT"].Rows) { try { if (internalNotification) Brol brol = AccessBrolDao.Instance.getBrol(brolRow); if (internalNotification) { notify(new Notification(Notification.VERBOSE.internalNotification, "brolStart", String.Format("Chargement de l'ouvrage {0}/{1} : {2}", ++mbCur, mbCount, brol.Title), this)); } foreach (DataRow catRow in brolRow.GetChildRows(dr)) { brol.addCategory(AccessBrolDao.Instance.getCategory(catRow)); } if (internalNotification) foreach (DataRow actorRow in brolRow.GetChildRows(drActors)) { brol.addActor(AccessBrolDao.Instance.getActor(actorRow)); } foreach (DataRow serieRow in brolRow.GetChildRows(drSerie)) { brol.addSerieItem(AccessBrolDao.Instance.getSerieItem(serieRow)); } if (internalNotification) brols.Add(brol); } catch (BuildObjectException boe) { } finally { if (internalNotification) } } } catch (Exception eAddAct) { } if (internalNotification) notify(new Notification(Notification.VERBOSE.internalNotification, "lastBrol", String.Format("Fin des {0} chargements", mbCount), this)); } catch (Exception fillMediaEx) { } return brols; } #endregion } }
Structure et Fichiers du projet
Afficher/masquer...Icône | Nom | Taille | Modification |
Icône | Nom | Taille | Modification |
| _ | Répertoire parent | 0 octets | 1731764241 16/11/2024 14:37:21 |
| _ | utils | 0 octets | 1541007203 31/10/2018 18:33:23 |
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-model/dao/msaccess//AccessExporterDao.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.