NoChangeImporterDao.cs
Description du code
NoChangeImporterDao.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# (NoChangeImporterDao.cs) (586 lignes)
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Collections; using System.Data.Common; using System.Data; using System.Drawing; using be.gaudry.observer; using be.gaudry.model; namespace be.gaudry.bibliobrol.model.dao.mysql { public sealed class NoChangeImporterDao : Observable, IImporterDao { private String conStr; #region singleton static NoChangeImporterDao instance = null; private DbProviderFactory dbpf; NoChangeImporterDao() { dbpf = ((MySQLFactory)MySQLFactory.Instance).getDbpf(); conStr = ((MySQLFactory)MySQLFactory.Instance).getConnectionString(); } public static NoChangeImporterDao Instance { get { lock (padlock) { if (instance == null) { } return instance; } } } #endregion #region IImporter Members /// <summary> /// Deserialize images /// </summary> /// <param name="path">(String) path of binary import file</param> /// <returns>A list of images</returns> public List<Image> importImages(string path) { FileStream fs = null; try { return images; } catch (FileNotFoundException) { notify(new Notification(Notification.VERBOSE.criticalError, "Importation des images", String.Format("Fichier {0} non trouvé.", path), this)); } catch (Exception e) { } finally { fs.Close(); } } /// <summary> /// Deserialize mediabrols /// Search existings mediabrols which not match exactly with new list items (don't check id's). /// </summary> /// <param name="path">(String) path of binary import file</param> public void importBinaryMediaBrol(string path) { DateTime startDateTime = DateTime.Now; FileStream fs = null; Object deserializedList = null; int count = 0; try { count = castList(deserializedList); } catch (FileNotFoundException) { notify(new Notification(Notification.VERBOSE.criticalError, "Importation", String.Format("Fichier {0} non trouvé.",path), this)); return; } catch (Exception e) { return; } finally { if (fs != null) fs.Close(); notify(new Notification(Notification.VERBOSE.internalNotification, "lastBrol", String.Format("Fin des {0} chargements", count), this)); notify(new Notification(Notification.VERBOSE.internalNotification, "End", String.Format("Fin de tous les traitements ({0})", Units.getDelay(startDateTime)), this)); } } #endregion #region private methods /// <summary> /// Test if deserialized object matches with a list of brols or a list of mediabrols /// And call appropriate method to import items /// </summary> /// <param name="deserializedList"></param> private int castList(object deserializedList) { int count; { //first attempt : is it a list of brols ? List<Brol> importedList = (List<Brol>)deserializedList; count = importedList.Count; notify(new Notification(Notification.VERBOSE.internalNotification, "count", count.ToString(), this)); importBrols(importedList); } { //second attempt : is it a list of mediabrols ? List<MediaBrol> importedList = (List<MediaBrol>)deserializedList; count = importedList.Count; notify(new Notification(Notification.VERBOSE.internalNotification, "count", count.ToString(), this)); importMediabrols(importedList); } else { count = 0; notify(new Notification(Notification.VERBOSE.error, "Importation", "Le fichier importé ne comporte ni ouvrage, ni exemplaire. Il est possible qu'il soit corrompu." , this)); } return count; } private void saveConflicts(List<IBrol> conflictList) { if (conflictList.Count > 0) { DateTime dt = DateTime.Now; StringBuilder saveConflictPath = new StringBuilder(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); saveConflictPath.Append(System.IO.Path.DirectorySeparatorChar); saveConflictPath.Append("brolConflict"); saveConflictPath.Append(dt.Year); if (dt.Month < 10) saveConflictPath.Append("0"); saveConflictPath.Append(dt.Month); if (dt.Day < 10) saveConflictPath.Append("0"); saveConflictPath.Append(dt.Day); if (dt.Minute < 10) saveConflictPath.Append("0"); saveConflictPath.Append(dt.Minute); saveConflictPath.Append(".bed"); "{0} éléments semblent déjà présents dans l'application. Vous pouvez toutefois importer ces éléments depuis le fichier suivant : {1}\n\nListe des éléments de ce fichier :\n\n", conflictList.Count, saveConflictPath.ToString())); { foreach (Brol brol in conflictList) str.AppendLine(brol.Title); } { foreach (MediaBrol mediabrol in conflictList) str.AppendLine(mediabrol.Brol.Title); } //exportation of conflicts list FileStream fs = NoChangeExporterDao.Instance.getFileStream(saveConflictPath.ToString(), FileMode.OpenOrCreate, FileAccess.Write); if (fs == null) { notify(new Notification(Notification.VERBOSE.criticalError, "Exportation des conflits", "Impossible de trouver un flux de sortie", this)); str.AppendLine("ERREUR : Impossible de trouver un flux de sortie"); } else { try { bf.Serialize(fs, conflictList); notify(new Notification(Notification.VERBOSE.internalNotification, "Exportation des conflits", String.Format("Les éléments en conflits ont été sauvés sous {0}",saveConflictPath.ToString()), this)); } catch (Exception eSer) { str.AppendLine(eSer.Message); } finally { fs.Close(); } } } } /// <summary> /// Check imported mediabrols. /// If a mediabrol don't exists, insert it. /// If an actor or a categorie don't exists, insert it. /// </summary> /// <param name="importedList">Deserialized mediabrols</param> private void importMediabrols(List<MediaBrol> importedList) { "Le fichier contient des exemplaires. Cette méthode n'est pour l'instant implémentée que pour des ouvrages.", this)); } /// <summary> /// Check imported brols. /// If a brol don't exists, insert it. /// If an actor or a categorie don't exists, insert it. /// </summary> /// <param name="importedList">Deserialized brols</param> private void importBrols(List<Brol> importedList) { int foundId; DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbCon.ConnectionString = conStr; dbDa.SelectCommand = dbCon.CreateCommand(); //todo : getTypesHashtable with , dbCon, dbDa Hashtable types = getTypesHashtable(); //todo : getCategoriesHashtable with , dbCon, dbDa Hashtable categories = getCategoriesHashtable(dbCon, dbDa); //todo : getPersonsHashtable with , dbCon, dbDa Hashtable persons = getPersonsHashtable(); // load all persons and categories form bibliobrol to adapt ids // and check if we need to insert new item //Check imported brols dbCon.Open(); foreach (Brol importedBrol in importedList) { foundId = 0; //test if type exists if (types.ContainsKey(importedBrol.BrolType.Name.ToUpper())) importedBrol.BrolType.Id = (int)types[importedBrol.BrolType.Name.ToUpper()]; else { //add type if not exists //modify brol type id importedBrol.BrolType.Id = NoChangeConfigDao.Instance.insertBrolType(importedBrol.BrolType, dbCon, dbDa); //insert into existing types.Add(importedBrol.BrolType.Name.ToUpper(), importedBrol.BrolType.Id); notify(new Notification(Notification.VERBOSE.internalNotification, "Ajout d'un type", String.Format("Ajout du type {0} dans l'application"), this)); } //test if brol exists dbDa.SelectCommand.CommandText = String.Format("SELECT id FROM item WHERE UCASE(itemTitle)='{0}'", MySQLUtils.escapeAndTrim(importedBrol.Title.ToUpper())); notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); try { foundId = (int)dbDa.SelectCommand.ExecuteScalar(); notify(new Notification(Notification.VERBOSE.debug, "foundId : " + foundId + " for " + importedBrol.Title, "", this)); } catch (Exception){} if (foundId > 0) { //conflict //importedBrol.Id = foundId; notify(new Notification(Notification.VERBOSE.internalNotification, "Conflit", String.Format("L'élément {0} semble en conflit avec un élément existant.", importedBrol.Title), this)); conflicts.Add(importedBrol);} else { insertImportedBrol(importedBrol, dbCon, dbDa, types, categories, persons); notify(new Notification(Notification.VERBOSE.internalNotification, "Import", String.Format("L'élément {0} est correstement importé.", importedBrol.Title), this)); } } dbCon.Close(); saveConflicts(conflicts); } /// <summary> /// Insert a new brol from import file /// </summary> /// <param name="importedBrol"></param> /// <param name="dbCon"></param> /// <param name="dbDa"></param> /// <param name="types"></param> /// <param name="categories"></param> /// <param name="persons"></param> /// <returns></returns> private int insertImportedBrol(Brol importedBrol, DbConnection dbCon, DbDataAdapter dbDa, Hashtable types, Hashtable categories, Hashtable persons) { if (dbDa.InsertCommand == null) dbDa.InsertCommand = dbCon.CreateCommand(); String key; importedBrol.Id = -1;//we need to set this value to insert as new item (!!!! otherwise we UPDATE AN EXISTING ITEM !!!) foreach (BrolCategory cat in importedBrol.Categories) { key = cat.Name.ToUpper()+importedBrol.BrolType.Id; //exists into bibliobrol if (categories.Contains(key)) { cat.Id = (int)categories[key]; } else { cat.Status = STATUS.toAppAdd; //insert new category into bibliobrol and set new id cat.Id = NoChangeConfigDao.Instance.insertCategory(cat, importedBrol.BrolType, dbCon, dbDa); notify(new Notification(Notification.VERBOSE.internalNotification, "Ajout", String.Format("La catégorie {0} est ajoutée.", cat.Name), this)); categories.Add(key, cat.Id); } cat.Status = STATUS.toAdd; } foreach (Actor actor in importedBrol.Actors) { key = getPersonKey(actor); //exists into bibliobrol if (persons.Contains(key)) { actor.Id = (int)persons[key]; } else { //todo : if person img exists, prompt to delete it (it is probably an img from another actor) actor.Status = STATUS.toAppAdd; actor.Id = -1;//to force insertion notify(new Notification(Notification.VERBOSE.internalNotification, "Ajout", String.Format("La personne {0} est ajoutée.", actor.Display), this)); persons.Add(key, actor.Id); } actor.Status = STATUS.toAdd; } return NoChangeBrolDao.Instance.insertBrol(importedBrol, dbCon, dbDa, true); } /// <summary> /// Check imported brols. /// If a brol don't exists, insert it. /// If an actor or a categorie don't exists, insert it. /// </summary> /// <param name="importedList">Deserialized mediabrols</param> /// <returns>(List IBrol)List of conflict brols</returns> private List<IBrol> importConflictBrols(List<IBrol> importedList) { /*Brol existingBrol; List<Brol> existingBrols = null; int[] brolIds = new int[1]; StringBuilder str = new StringBuilder("Résultat de l'importation"); Hashtable categories = getCategoriesHashtable(); Hashtable persons = getPersonsHashtable(); DbConnection dbCon = dbpf.CreateConnection(); DbDataAdapter dbDa = dbpf.CreateDataAdapter(); dbCon.ConnectionString = conStr; dbDa.SelectCommand = dbCon.CreateCommand(); // load all persons and categories form bibliobrol to adapt ids // and check if we need to insert new item //todo : loadpersons with , dbCon, dbDa //todo : loadCategories with , dbCon, dbDa //Check imported brols String key;//key to test foreach (Brol importedBrol in importedList) { notify(new Notification(Notification.VERBOSE.internalNotification, "count2", "6", this)); notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 1", this)); //load brol if exists //ds = new DataSet(); dbDa.SelectCommand.CommandText = String.Format("SELECT id FROM item WHERE UCASE(itemTitle)='{0}'", importedBrol.Title.Trim().ToUpper().Replace("'", "''")); notify(new Notification(Notification.VERBOSE.advancedOperation, dbDa.SelectCommand.CommandText, this)); dbCon.Open(); try { brolIds[0] = (int)dbDa.SelectCommand.ExecuteScalar(); existingBrols = AccessExporterDao.Instance.loadSelectedBrols(brolIds, dbCon, dbDa, false); } catch (Exception) { } dbCon.Close(); notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 2", this)); if (existingBrols != null && existingBrols.Count > 0) { existingBrol = existingBrols[0]; } else { existingBrol = new Brol(); existingBrol.Title = importedBrol.Title; } foreach (BrolCategory cat in importedBrol.Categories) { key = cat.Name.ToUpper() + existingBrol.BrolType.Id; //exists into bibliobrol if (categories.Contains(key)) { cat.Id = (int)categories[key]; //check with found Brol item cat.Status = STATUS.none; foreach (BrolCategory tempCat in existingBrol.Categories) { if (tempCat.Id == cat.Id) { cat.Status = STATUS.toAdd; break; } } //cat exists into bibliobrol, but not into existing brol if (cat.Status.Equals(STATUS.toAdd)) { existingBrol.addCategory(cat); } } //don't exists into bibliobrol (and don't exists into existing brol) else { cat.Status = STATUS.toAppAdd; //insert new category into bibliobrol cat.Id = AccessConfigDao.Instance.insertCategory(cat, existingBrol.BrolType, dbCon, dbDa); cat.Status = STATUS.toAdd; categories.Add(key, cat.Id); existingBrol.addCategory(cat); } } notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 3", this)); foreach (Actor actor in importedBrol.Actors) { key = getPersonKey(actor); //exists into bibliobrol if (persons.Contains(key)) { actor.Id = (int)persons[key]; //check with found Brol item STATUS = STATUS.none; foreach (Actor tempActor in existingBrol.Actors) { if (tempActor.Id == actor.Id) { STATUS = STATUS.toAdd; break; } } //person exists into bibliobrol, but actor not exists into current loaded brol if (STATUS.Equals(STATUS.toAdd)) { existingBrol.addActor(actor); } } //don't exists into bibliobrol (and don't exists into existing brol) else { STATUS = STATUS.toAppAdd; //insert new category into bibliobrol actor.Id = AccessPersonDao.Instance.insertPerson(actor.getPerson(), dbCon, dbDa, str); STATUS = STATUS.toAdd; persons.Add(key, actor.Id); existingBrol.addActor(actor); } } notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 4", this)); if (String.Empty.Equals(existingBrol.Comment) && !String.Empty.Equals(importedBrol.Comment)) { existingBrol.Comment = importedBrol.Comment; } if (String.Empty.Equals(existingBrol.Synopsis) && !String.Empty.Equals(importedBrol.Synopsis)) { existingBrol.Synopsis = importedBrol.Synopsis; } if ((new DateTime(0L)).Equals(existingBrol.Date) && !(new DateTime(0L)).Equals(importedBrol.Date)) { existingBrol.Date = importedBrol.Date; } if (existingBrol.Cotation < 1 && importedBrol.Cotation > 0) { existingBrol.Cotation = importedBrol.Cotation; } notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 5", this)); if (existingBrol.Id < 0) { AccessBrolDao.Instance.insertBrol(existingBrol, dbCon, dbDa, false); } else { AccessBrolDao.Instance.updateBrol(existingBrol, dbCon, dbDa, false, str); } notify(new Notification(Notification.VERBOSE.internalNotification, "pb2", "step 6", this)); str.AppendLine(String.Format("Ouvrage {0} : {1}", existingBrol.Id, existingBrol.Title)); notify(new Notification(Notification.VERBOSE.internalNotification, "brolEnd", "", this)); }*/ return null; } /// <summary> /// Get a Hashtable with all categories ids. /// key : name.toUpper()+typeId /// value : id /// </summary> /// <returns>Hashtable with categories ids</returns> private Hashtable getCategoriesHashtable(DbConnection dbCon, DbDataAdapter dbDa) { dbDa.SelectCommand.CommandText = "SELECT id, typeId, name FROM category"; notify(new Notification(Notification.VERBOSE.persistentOperation, dbDa.SelectCommand.CommandText, this)); try { dbDa.Fill(catsDt); foreach (DataRow row in catsDt.Rows) { { categories.Add(((String)row["name"]).ToUpper()+(int)row["typeId"], (int)row["id"]); } } } catch (Exception e) { notify(new Notification(Notification.VERBOSE.advancedOperation, "Chargement des catégories", e, this)); } /*foreach (BrolCategory c in AccessBrolDao.Instance.loadCategories(-2)) { categories.Add(c.Name.ToUpper(), c.Id); }*/ return categories; } /// <summary> /// Get a Hashtable with all persons ids. /// key : see String getPersonKey(Person person) method /// value : id /// </summary> /// <returns>Hashtable with persons ids</returns> private Hashtable getPersonsHashtable() { foreach (Person person in NoChangePersonDao.Instance.loadPersons()) { persons.Add(getPersonKey(person), person.Id); } return persons; } /// <summary> /// Get a Hashtable with all types ids. /// key : type name /// value : id /// </summary> /// <returns>Hashtable with persons ids</returns> private Hashtable getTypesHashtable() { foreach (BrolType type in NoChangeConfigDao.Instance.loadBrolTypes()) { types.Add(type.Name.ToUpper(), type.Id); } return types; } /// <summary> /// Get a key for a person : FirstName.ToUpper() + LastName.ToUpper(); /// </summary> /// <param name="person">(Person) from which we need a key</param> /// <returns>(String)person key</returns> private String getPersonKey(Person person) { return person.FirstName.ToUpper() + person.LastName.ToUpper(); } #endregion } }
Structure et Fichiers du projet
Afficher/masquer...Icône | Nom | Taille | Modification |
Icône | Nom | Taille | Modification |
| _ | Répertoire parent | 0 octets | 1734937716 23/12/2024 08:08:36 |
| _ | 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.
Nederlandse vertaling
U hebt gevraagd om deze site in het Nederlands te bezoeken. Voor nu wordt alleen de interface vertaald, maar nog niet alle inhoud.Als je me wilt helpen met vertalingen, is je bijdrage welkom. Het enige dat u hoeft te doen, is u op de site registreren en mij een bericht sturen waarin u wordt gevraagd om u toe te voegen aan de groep vertalers, zodat u de gewenste pagina's kunt vertalen. Een link onderaan elke vertaalde pagina geeft aan dat u de vertaler bent en heeft een link naar uw profiel.
Bij voorbaat dank.
Document heeft de 16/10/2009 gemaakt, de laatste keer de 26/10/2018 gewijzigd
Bron van het afgedrukte document:https://www.gaudry.be/nl/cs-bibliobrol-source-rf-model/dao/mysql//NoChangeImporterDao.cs.html
De infobrol is een persoonlijke site waarvan de inhoud uitsluitend mijn verantwoordelijkheid is. De tekst is beschikbaar onder CreativeCommons-licentie (BY-NC-SA). Meer info op de gebruiksvoorwaarden en de auteur.