From d092d4a65da6adefd55ef6342ba699114a520a28 Mon Sep 17 00:00:00 2001 From: CSiCoAlm Date: Sat, 27 Dec 2025 15:12:42 +0100 Subject: [PATCH] Inserisco nel DB le tabelle per i racconti MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Inserito nel DB le tabelle per l'archivio dei racconti - Inserito gestione in memoria del DB (manca ottimizzazione lasciando l'archivio su file come fatto per ATDB) - Inserito classe cRac per rappresentare un racconto ToDo: - Aggiungere gestione parallela della FIFO secondo vecchi modello per aumentare il feedback alla UI - Inserire anche l'estrazione dei racconti - Per ora metto tutto il DB in memoria, poi dovrò ottimizzare come su ATDB --- Src/A69WD/.vs/A69WD.csproj.dtbcache.json | 2 +- Src/A69WD/A69WD.csproj | 2 + Src/A69WD/A69WD.csproj.user | 2 +- Src/A69WD/Data/DBTools.cs | 683 +++++++++++++++---- Src/A69WD/Data/cNota.cs | 38 ++ Src/A69WD/Data/cRac.cs | 830 +++++++++++++++++++++++ 6 files changed, 1431 insertions(+), 126 deletions(-) create mode 100644 Src/A69WD/Data/cNota.cs create mode 100644 Src/A69WD/Data/cRac.cs diff --git a/Src/A69WD/.vs/A69WD.csproj.dtbcache.json b/Src/A69WD/.vs/A69WD.csproj.dtbcache.json index 2e178ed..0b1ca31 100644 --- a/Src/A69WD/.vs/A69WD.csproj.dtbcache.json +++ b/Src/A69WD/.vs/A69WD.csproj.dtbcache.json @@ -1 +1 @@ -{"RootPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD","ProjectFileName":"A69WD.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"App.cs"},{"SourceFile":"Data\\DBTools.cs"},{"SourceFile":"Net\\ATLink.cs"},{"SourceFile":"Net\\ATLinkState.cs"},{"SourceFile":"Net\\cA69Engine.cs"},{"SourceFile":"Net\\DownloadClient.cs"},{"SourceFile":"Net\\frmDownloader.cs"},{"SourceFile":"Net\\frmDownloader.Designer.cs"},{"SourceFile":"Data\\eLinkState.cs"},{"SourceFile":"General\\Cfg.cs"},{"SourceFile":"General\\cTools.cs"},{"SourceFile":"Logger.cs"},{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"Properties\\Resources.Designer.cs"},{"SourceFile":"Properties\\Settings.Designer.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.8.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\HtmlAgilityPack.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\System.Data.SQLite.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Deployment.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Drawing.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Windows.Forms.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD\\bin\\Debug\\A69WD.exe","OutputItemRelativePath":"A69WD.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} \ No newline at end of file +{"RootPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD","ProjectFileName":"A69WD.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"App.cs"},{"SourceFile":"Data\\DBTools.cs"},{"SourceFile":"Net\\eLinkState.cs"},{"SourceFile":"Net\\cLink_A69.cs"},{"SourceFile":"Service\\Service_Crawler.cs"},{"SourceFile":"Site\\cSite_A69.cs"},{"SourceFile":"UI\\frmDownloader.cs"},{"SourceFile":"UI\\frmDownloader.Designer.cs"},{"SourceFile":"General\\Cfg.cs"},{"SourceFile":"General\\cTools.cs"},{"SourceFile":"General\\Logger.cs"},{"SourceFile":"Net\\iLink.cs"},{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"Site\\iSiteType.cs"},{"SourceFile":"Properties\\Resources.Designer.cs"},{"SourceFile":"Properties\\Settings.Designer.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.8.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\HtmlAgilityPack.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\System.Data.SQLite.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Deployment.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Drawing.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Windows.Forms.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD\\bin\\Debug\\A69WD.exe","OutputItemRelativePath":"A69WD.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} \ No newline at end of file diff --git a/Src/A69WD/A69WD.csproj b/Src/A69WD/A69WD.csproj index 7aad2c7..9497c87 100644 --- a/Src/A69WD/A69WD.csproj +++ b/Src/A69WD/A69WD.csproj @@ -59,6 +59,8 @@ + + diff --git a/Src/A69WD/A69WD.csproj.user b/Src/A69WD/A69WD.csproj.user index 56fd5d8..e0be25f 100644 --- a/Src/A69WD/A69WD.csproj.user +++ b/Src/A69WD/A69WD.csproj.user @@ -1,6 +1,6 @@ - ProjectFiles + ShowAllFiles \ No newline at end of file diff --git a/Src/A69WD/Data/DBTools.cs b/Src/A69WD/Data/DBTools.cs index 816b6b0..043224f 100644 --- a/Src/A69WD/Data/DBTools.cs +++ b/Src/A69WD/Data/DBTools.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Data.SQLite; using A69WD.Net; +using System.Drawing; namespace A69WD { @@ -77,17 +78,62 @@ namespace A69WD { if (cn == null) cn = new System.Data.SQLite.SQLiteConnection("data source=:memory:"); cn.Open(); // Creo tabelle in uso - SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(), cn); + SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(false), cn); int res = cmd.ExecuteNonQuery(); if (res > 1) Logger.Log(new object[] { "Error Code: ER01022", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaA69DB())={0}", res) }); // Attach DB A69DB su File cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn); res = cmd.ExecuteNonQuery(); - if (res > 1) Logger.Log(new object[] { "Error Code: ER01026b", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS DBfile)", res) }); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026b", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) }); // Copio i dati cmd = new SQLiteCommand("INSERT INTO [LinksLog] SELECT * FROM A69DBfile.LinksLog", cn); res = cmd.ExecuteNonQuery(); if (res < 1) Logger.Information(string.Format("Info Code: IN01001 - Nessun LinksLog riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Voti] SELECT * FROM A69DBfile.Voti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01002 - Nessun Voti riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Racconti] SELECT * FROM A69DBfile.Racconti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01003 - Nessun Racconti riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Autori] SELECT * FROM A69DBfile.Autori", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01004 - Nessun Autori riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Origini] SELECT * FROM A69DBfile.Origini", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01005 - Nessun Origini riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Tags] SELECT * FROM A69DBfile.Tags", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01006 - Nessun Tags riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Notes] SELECT * FROM A69DBfile.Notes", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01007 - Nessun Notes riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Trame] SELECT * FROM A69DBfile.Trame", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01008 - Nessun Trame riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Segnalini] SELECT * FROM A69DBfile.Segnalini", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Segnalini riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Users] SELECT * FROM A69DBfile.Users", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Users riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Aut] SELECT * FROM A69DBfile.Links_Rac_Aut", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Aut riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Not] SELECT * FROM A69DBfile.Links_Rac_Not", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Not riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Tag] SELECT * FROM A69DBfile.Links_Rac_Tag", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Tag riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Ori] SELECT * FROM A69DBfile.Links_Rac_Ori", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Ori riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Vot] SELECT * FROM A69DBfile.Links_Rac_Vot", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Vot riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Sng] SELECT * FROM A69DBfile.Links_Rac_Sng", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Sng riportato sul DB in memoria.", res)); // Detach del DB su File } catch (Exception ex) { Logger.Log(new object[] { "Error Code: ER01020", "Errore in ATLib.Data.DBtools() durante il trasferimento in memoria del DB", ex }); @@ -107,16 +153,86 @@ namespace A69WD { // Copio i valori creati: solo se il DB è OK: if (!DB_ok) return Res; try { - // Copio i dati saltando i doppioni - // Elimino i dati vecchi in A69DB: - SQLiteCommand cmd = new SQLiteCommand("DELETE FROM A69DBfile.LinksLog", cn); - int res = cmd.ExecuteNonQuery(); - if (res < 1) Logger.Information(string.Format("Info Code: IN03001 - Nessun LinksLog cancellato dal file del DB.", res)); - // Inserisco i nuovi dati in A69DB: + // Detach del DB su File + SQLiteCommand cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn); + int res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) }); + + // Elimino il file rinominandolo per backup + string FullNameDB = System.IO.Path.Combine(Cfg.Settings.PathDB,Cfg.Settings.DBName); + string FullNameBkDB = FullNameDB.Replace(".db","_BK_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".db"); + System.IO.File.Move(FullNameDB, FullNameBkDB); + + // Creo nuovo file vuoto su cui riportare i dati dalla memoria: + using (SQLiteConnection cnTmp = new SQLiteConnection(Cfg.Settings.DBConnectionString)) { + cnTmp.Open(); + cmd = new SQLiteCommand(CreaA69DB(false), cnTmp); + res = cmd.ExecuteNonQuery(); + if (res < 0) Logger.Log(new object[] { "Error Code: ER03011", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaDB(false, false))={0}", res) }); + cnTmp.Close(); + cnTmp.Dispose(); + } + + // Attach DB su File + cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn); + res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER03026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) }); + + // Copio i dati cmd = new SQLiteCommand("INSERT INTO A69DBfile.LinksLog SELECT * FROM LinksLog", cn); res = cmd.ExecuteNonQuery(); if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun LinksLog riportato sul file del DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Voti SELECT * FROM Voti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun Voti riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Racconti SELECT * FROM [Racconti]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03003 - Nessun Racconti riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Autori SELECT * FROM [Autori]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03004 - Nessun Autori riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Origini SELECT * FROM [Origini]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03005 - Nessun Origini riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Tags SELECT * FROM [Tags]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03006 - Nessun Tags riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Notes SELECT * FROM [Notes]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03007 - Nessun Notes riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Trame SELECT * FROM [Trame]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03008 - Nessun Trame riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Segnalini SELECT * FROM [Segnalini]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03009 - Nessun Segnalini riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Users SELECT * FROM [Users]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03010 - Nessun Users riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Aut SELECT * FROM [Links_Rac_Aut]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03011 - Nessun Links_Rac_Aut riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Not SELECT * FROM [Links_Rac_Not]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03012 - Nessun Links_Rac_Not riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Tag SELECT * FROM [Links_Rac_Tag]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03013 - Nessun Links_Rac_Tag riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Ori SELECT * FROM [Links_Rac_Ori]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03014 - Nessun Links_Rac_Ori riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Vot SELECT * FROM [Links_Rac_Vot]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03015 - Nessun Links_Rac_Vot riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Sng SELECT * FROM [Links_Rac_Sng]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03016 - Nessun Links_Rac_Sng riportato sul file DB.", res)); + + // Detach del DB su File + cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn); + res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) }); Res = true; } catch (Exception ex) { @@ -135,6 +251,7 @@ namespace A69WD { if (res > 1) Logger.Log(new object[] { "Error Code: IN03027", string.Format("Possibile errore in ATLib.Data.Dispose() - cmd.ExecuteNonQuery(VACUUM)={0}", res) }); conn.Close(); conn.Dispose(); + conn = null; Res = Res && true; } catch (Exception ex) { Logger.Log(new object[] { "Error Code: ER03003", "Errore in ATLib.Data.Dispose() durante la compressione del DB", ex }); @@ -146,7 +263,7 @@ namespace A69WD { } } - private string CreaA69DB() { + private string CreaA69DB(bool FixedData = true) { StringBuilder sb = new StringBuilder(); @@ -167,6 +284,425 @@ namespace A69WD { sb.AppendLine("-- "); sb.AppendLine("-- "); sb.AppendLine("------------------------------------------------------------------------------"); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE TABLE [Racconti] ( -- COMMENT "); + sb.AppendLine(" [IDrac] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [Title] TEXT NOT NULL DEFAULT 'Unknown', -- COMMENT 'Titolo del racconto' "); + sb.AppendLine(" [SubTitle] TEXT NOT NULL DEFAULT '', -- COMMENT 'Sottotitolo del racconto' "); + sb.AppendLine(" [Creato] TEXT NOT NULL DEFAULT '2000/12/31', -- COMMENT 'Data di creazione del racconto' "); + sb.AppendLine(" [Aggiornato] TEXT NOT NULL DEFAULT '2000/12/31' -- COMMENT 'Data dell''ultima modifica al racconto' "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Autori] ( -- COMMENT='Tabella con tutti gli Autori dei Racconti dell''archivio.' "); + sb.AppendLine(" [IDaut] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [Autore] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Nickname dell autore', "); + sb.AppendLine(" UNIQUE(Autore) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Notes] ( -- COMMENT 'Tabella per rappresentare tramite coppia key-value delle note da associare ad un racconto. Da utilizzare per salvare il link da cui ho downloadato il racconto, oppure l''eventuale riassunto, o altro.' "); + sb.AppendLine(" [IDnot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della nota' "); + sb.AppendLine(" [NKey] TEXT NON NULL DEFAULT 'Nota', -- COMMENT 'Nota Key: Identificativo del tipo di nota: Resume, Link, OriginalID, ...' "); + sb.AppendLine(" [NVal] TEXT NON NULL DEFAULT '', -- COMMENT 'Nota Value: valore della nota' "); + sb.AppendLine(" UNIQUE(NKey, NVal) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Origini] ( -- COMMENT 'Tabella con tutte le possibili Origini dei racconti.' "); + sb.AppendLine(" [IDori] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del origine' "); + sb.AppendLine(" [Origine] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Origine da cui ho preso il racconto' "); + sb.AppendLine(" UNIQUE(Origine) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Segnalini] ( -- COMMENT "); + sb.AppendLine(" [IDsng] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del segnalino' "); + sb.AppendLine(" [Linea] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Indice della linea che si vuole segnalare (0 inizio racconto)' "); + sb.AppendLine(" [Segnalino] TEXT NON NULL DEFAULT 'Read', -- COMMENT 'Descrizione del segnalino per semplice comprensione (Read pe ril segnalino automatico con il punto di lettura)' "); + sb.AppendLine(" UNIQUE(Linea, Segnalino) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Tags] ( -- COMMENT 'Tabella con tutte i tag che vogliamo associare ai Racconti.' "); + sb.AppendLine(" [IDtag] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del Tag' "); + sb.AppendLine(" [Tag] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Nome descrittivo del Tag' "); + sb.AppendLine(" UNIQUE(Tag) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Trame] ( -- COMMENT 'Tabella con tutte le Trame dei Racconti.' "); + sb.AppendLine(" [IDtra] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della trama' "); + sb.AppendLine(" [IDrac] INTEGER NON NULL, -- COMMENT 'Identificativo del racconto a cui la trama corrisponde (univoco perchè solo una trama per racconto). Rappresenta la relazione 1-1 fra Racconti-Trame' "); + sb.AppendLine(" [Trama] TEXT NON NULL, -- COMMENT 'Trama del racconto' "); + sb.AppendLine(" UNIQUE(IDrac), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Voti] ( -- COMMENT 'Tabella con tutti i possibili Voti associabili ai Racconti.' "); + sb.AppendLine(" [IDvot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del voto' "); + sb.AppendLine(" [Rating] INTEGER CHECK (Rating>-1 AND Rating<11), -- COMMENT 'Valore del voto per statistiche' "); + sb.AppendLine(" [Voto] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Voto da attribuire ad un racconto' "); + sb.AppendLine(" UNIQUE(Voto) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Users] ( -- COMMENT 'Elenco degli utenti abilitati della web application' "); + sb.AppendLine(" [IDusr] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo dell''utente' "); + sb.AppendLine(" [Username] TEXT NOT NULL, -- COMMENT 'Username di identificazione dell''utente. Viene scelto dall''utente stesso al momento della registrazione' "); + sb.AppendLine(" [Password] TEXT NOT NULL, -- COMMENT 'Hash della password scelta dall''utente' "); + sb.AppendLine(" [Level] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Livello dell''utente nella web application. Di default è posto a 0 e solo l''amministratore può variarlo' "); + sb.AppendLine(" UNIQUE(Username) "); + sb.AppendLine(" ); "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione delle tabelle per rappresentare i link fra i record "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Aut] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e i propri Autori.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Autori' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDaut] INTEGER NOT NULL, -- COMMENT 'Identificativo dell''autore' "); + sb.AppendLine(" UNIQUE(IDrac, IDaut), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDaut`) REFERENCES `Autori`(`IDaut`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE Links_Rac_Not ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le note (coppie key-Value).' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Notes' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDnot] INTEGER NOT NULL, -- COMMENT 'Identificativo della nota' "); + sb.AppendLine(" UNIQUE(IDrac, IDnot), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDnot`) REFERENCES `Notes`(`IDnot`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Tag] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le propietà.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Tags' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDtag] INTEGER NOT NULL, -- COMMENT 'Identificativo della propietà' "); + sb.AppendLine(" UNIQUE(IDrac, IDtag), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDtag`) REFERENCES `Tags`(`IDtag`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Ori] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e le origini.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Origini' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDori] INTEGER NOT NULL, -- COMMENT 'Identificativo dell'' origine' "); + sb.AppendLine(" UNIQUE(IDrac, IDori), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDori`) REFERENCES `Origini`(`IDori`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Vot] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e i voti.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Voti' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDvot] INTEGER NOT NULL, -- COMMENT 'Identificativo del voto' "); + sb.AppendLine(" UNIQUE(IDrac), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDvot`) REFERENCES `Voti`(`IDvot`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Sng] ( -- COMMENT 'Tabella per rappresentare la relazione 1-Molti fra i Racconti e i segnalini.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Segnalini' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDsng] INTEGER NOT NULL, -- COMMENT 'Identificativo del segnalino' "); + sb.AppendLine(" UNIQUE(IDsng), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDsng`) REFERENCES `Segnalini`(`IDsng`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione degli indici: "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE INDEX IDX_Voti ON Voti ( Voto COLLATE NOCASE ); "); + if (FixedData) { + sb.AppendLine(" -- "); + sb.AppendLine(" -- Inserimento dei dati iniziali noti: "); + sb.AppendLine(" -- "); + sb.AppendLine(" INSERT INTO `origini` (`IDori`, `Origine`) VALUES "); + sb.AppendLine(" (1, 'Unknown'), "); + sb.AppendLine(" (2, 'Autocreazione'), "); + sb.AppendLine(" (3, 'A69'), "); + sb.AppendLine(" (4, 'eRac'), "); + sb.AppendLine(" (5, 'Mil'); "); + sb.AppendLine(" INSERT INTO `users` (`IDusr`, `Username`, `Password`, `Level`) VALUES "); + sb.AppendLine(" (1, 'root', 'e10adc3949ba59abbe56e057f20f883e', 9), "); + sb.AppendLine(" (2, 'Mrk', 'ABC', 8), "); + sb.AppendLine(" (3, 'reader', 'A', 5), "); + sb.AppendLine(" (4, 'guest', 'A', 0); "); + sb.AppendLine(" INSERT INTO `voti` (`IDvot`, `Rating`, `Voto`) VALUES "); + sb.AppendLine(" (0, 0, 'Non Letto'), "); + sb.AppendLine(" (1, 1, 'Da Cancellare'), "); + sb.AppendLine(" (2, 2, 'Pessimo'), "); + sb.AppendLine(" (3, 3, 'Brutto'), "); + sb.AppendLine(" (4, 4, 'Scarso'), "); + sb.AppendLine(" (5, 5, 'Insufficiente'), "); + sb.AppendLine(" (6, 6, 'Sufficiente'), "); + sb.AppendLine(" (7, 7, 'Carino'), "); + sb.AppendLine(" (8, 8, 'Bello'), "); + sb.AppendLine(" (9, 9, 'Ottimo'), "); + sb.AppendLine(" (10, 10, 'Da Collezione'); "); + } + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione dei trigger: "); + sb.AppendLine(" -- "); + sb.AppendLine(" --- Triggers sulla tabella Racconti: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Racconti_Delete "); + sb.AppendLine(" AFTER DELETE ON Racconti "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" "); + sb.AppendLine(" DELETE FROM Links_Rac_Aut WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Ori WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Tag WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Not WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Vot WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Sng WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Trame WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Notes WHERE IDnot NOT IN(SELECT Notes.IDnot FROM Notes, Links_Rac_not WHERE Notes.IDnot = Links_Rac_Not.IDnot); "); + sb.AppendLine(" DELETE FROM Segnalini WHERE IDsng NOT IN(SELECT Segnalini.IDsng FROM Segnalini, Links_Rac_Sng WHERE Segnalini.IDsng = Links_Rac_Sng.IDsng); "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Autori: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Autori_Delete "); + sb.AppendLine(" BEFORE DELETE ON Autori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Aut WHERE IDaut=OLD.IDaut) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore ancora riferito a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Origini: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Origini_Delete "); + sb.AppendLine(" BEFORE DELETE ON Origini "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Ori WHERE IDori=OLD.IDori) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Insert_Origine ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Update_Origine ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Tags: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Tags_Delete "); + sb.AppendLine(" BEFORE DELETE ON Tags "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Tag WHERE IDtag=OLD.IDtag) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Notes: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Notes_Delete "); + sb.AppendLine(" BEFORE DELETE ON Notes "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Not WHERE IDnot=OLD.IDnot) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Trame: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Trama_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Trama_Insert "); + sb.AppendLine(" BEFORE INSERT ON Trame "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Trama_Update_Trama "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Trame "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Segnalini: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Segnalini_Delete "); + sb.AppendLine(" BEFORE DELETE ON Segnalini "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Sng WHERE IDsng=OLD.IDsng) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino ancora riferito a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Aut: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Aut_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDaut ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Ori: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Ori_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDori ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Tag: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Tag_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDtag ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Not: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Not_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDnot ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Sng: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Sng_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato al Segnalino, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all Segnalino, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDsng ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE VIEW Autore_Browser_Autori AS "); + sb.AppendLine(" SELECT "); + sb.AppendLine(" IDaut, "); + sb.AppendLine(" Autore, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT COUNT(IDaut) "); + sb.AppendLine(" FROM Links_Rac_Aut "); + sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut "); + sb.AppendLine(" ) AS Num, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT AVG(Voti.IDvot) "); + sb.AppendLine(" FROM Links_Rac_Aut, "); + sb.AppendLine(" Links_Rac_Vot, "); + sb.AppendLine(" Voti "); + sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut AND "); + sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Aut.IDrac AND "); + sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND "); + sb.AppendLine(" Voti.IDvot <> 0 "); + sb.AppendLine(" ) AS Rate "); + sb.AppendLine(" FROM Autori "); + sb.AppendLine(" ORDER BY Num DESC, Rate DESC; "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Inserimento delle viste: "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE VIEW Tag_Browser_Tags AS "); + sb.AppendLine(" SELECT "); + sb.AppendLine(" IDtag, "); + sb.AppendLine(" Tag, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT COUNT(IDtag) "); + sb.AppendLine(" FROM Links_Rac_Tag "); + sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag "); + sb.AppendLine(" ) AS Num, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT AVG(Voti.IDvot) "); + sb.AppendLine(" FROM Links_Rac_Tag, "); + sb.AppendLine(" Links_Rac_Vot, "); + sb.AppendLine(" Voti "); + sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag AND "); + sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Tag.IDrac AND "); + sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND "); + sb.AppendLine(" Voti.IDvot <> 0 "); + sb.AppendLine(" ) AS Rate "); + sb.AppendLine(" FROM Tags "); + sb.AppendLine(" ORDER BY Num DESC, Rate DESC; "); + sb.AppendLine("-- "); + sb.AppendLine("-- "); + sb.AppendLine("------------------------------------------------------------------------------"); #endregion return sb.ToString(); @@ -176,120 +712,13 @@ namespace A69WD { #endregion - - public int LoadData(List allLinks, List toDownload, List downloaded, List racLinks) { - //object obj = new Object(); - //lock (obj) { - // int Res = 0; - // try { - - // // Carico tutti i racconti non ancora downloadati completamente: - // System.Data.SQLite.SQLiteCommand cmd = new SQLiteCommand("SELECT [URL], [Tipo], [Status], [LastUp] FROM [LinksLog] WHERE [Tipo]='Rac' AND [Status]<>4", cn); // Donwloaded = 4 - // SQLiteDataReader rdr = cmd.ExecuteReader(); - // while (rdr.Read()) { - // string url = rdr["URL"] as string; - // allLinks.Add(url); - // toDownload.Add(url); - // racLinks.Add(url); - // Res++; - // } - - // // Carico ora tutti i racconti downloadati completamente per evitare doppioni: - // cmd = new SQLiteCommand("SELECT [URL], [Tipo], [Status], [LastUp] FROM [LinksLog] WHERE [Tipo]='Rac' AND [Status]=4", cn); // Donwloaded = 4 - // rdr = cmd.ExecuteReader(); - // while (rdr.Read()) { - // string url = rdr["URL"] as string; - // allLinks.Add(url); - // racLinks.Add(url); - // Res++; - // } - - // } catch (Exception ex) { - // Logger.Log(new object[] { "Error Code: DB07003", "Errore in Data.DBTools.LoadData()", ex }); - // if (Res > 0) Res = -1 * Res; - // } - // return Res; - //} - return 0; - } - - public int SaveData(List allLinks, List toDownload, List downloaded, List racLinks) { - //object obj = new Object(); - //lock (obj) { - // int Res = 0; - // try { - // foreach (string link in racLinks) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.Donwloaded); } - // foreach (string link in toDownload) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.ToDownload); } - // foreach (string link in downloaded) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.Donwloaded); } - // } catch (Exception ex) { - // Logger.Log(new object[] { "Error Code: DB07003", "Errore in Data.DBTools.LoadData()", ex }); - // if (Res > 0) Res = -1 * Res; - // } - // return Res; - //} - return 0; - } - - - private bool LinkLogUpdtate(string url, string tip, eLinkState st) { - // object obj = new Object(); - // lock (obj) { - // Cancello riga (se non presente, non fa nulla) - // Inserisco riga - bool Res = false; - try { - // Cancello il link anche se non presente - System.Data.SQLite.SQLiteCommand cmd = new SQLiteCommand(string.Format("DELETE FROM [LinksLog] WHERE [URL]='{0}'", url), cn); - int res = cmd.ExecuteNonQuery(); - cmd = null; - // Inserisco il link come se fosse nuovo - cmd = new System.Data.SQLite.SQLiteCommand(); - cmd.Connection = cn; - cmd.CommandText = "INSERT INTO LinksLog (URL,Tipo,Status,LastUp)VALUES (@URL,@Tipo,@Status,@LastUp)"; - cmd.CommandType = System.Data.CommandType.Text; - System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@URL"; - param.DbType = global::System.Data.DbType.String; - param.SourceColumn = "URL"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@Tipo"; - param.DbType = global::System.Data.DbType.String; - param.SourceColumn = "Tipo"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@Status"; - param.DbType = global::System.Data.DbType.Int32; - param.SourceColumn = "Status"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@LastUp"; - param.DbType = global::System.Data.DbType.DateTime; - param.SourceColumn = "LastUp"; - cmd.Parameters.Add(param); - cmd.Parameters[0].Value = url; - cmd.Parameters[1].Value = tip; - cmd.Parameters[2].Value = st; - //if (InsertDate) { cmd.Parameters[3].Value = DateTime.Now; } else { cmd.Parameters[3].Value = DateTime.MaxValue; } - cmd.Parameters[3].Value = DateTime.Now; - res = cmd.ExecuteNonQuery(); - if (res != 1) { - Logger.Log(new object[] { "Error Code: DB06010", string.Format("DBTools.LinkLogUpdtate({0})={1}", url, res) }); - Res = false; - } else { - Res = true; - } - } catch (Exception ex) { - Logger.Log(new object[] { "Error Code: DB06001", string.Format("DBTools.LinkLogUpdtate({0})", url), ex }); - return false; - } finally { - //if ((cn != null) && (cn.State != System.Data.ConnectionState.Closed)) cn.Close(); - } - return Res; - // } // lock (obj) - } - - + + + /// + /// Ritorna lo stato di un link + /// + /// URL identificativo del link + /// Stato del link nel DB (ToDownload se link non presente nel DB) public eLinkState GetStateByURL(string url) { lock (objLock) { try { @@ -313,7 +742,12 @@ namespace A69WD { } } - + /// + /// Verifica se il link è già presente nel DB + /// + /// URL del link da testare + /// Offset temporale per la verifica (0 per l'intero DB) + /// True se URL presente, false altrimenti public bool IsPresent(string url, int timeOffset = 0) { lock (objLock) { try { @@ -425,6 +859,7 @@ namespace A69WD { // } // lock (obj) } + } // class DBTools diff --git a/Src/A69WD/Data/cNota.cs b/Src/A69WD/Data/cNota.cs new file mode 100644 index 0000000..566db36 --- /dev/null +++ b/Src/A69WD/Data/cNota.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace A69WD.Data { + + /// + /// Serve per gestire una nota che sarà la coppia di stringhe: {Key} - {Descrizione} + /// + public class cNota { + + public string Key { get; set; } + public string Description { get; set; } + + /// + /// Stringa di separazione fra i vari campi quando esprimo un elenco tramite una singola stringa + /// + private const string SEPARATORETXT = " -|- "; + + public cNota() { + Key = ""; + Description = ""; + } + + public cNota(string key, string description) { + Key = key; + Description = description; + } + + public override string ToString() { + return Key + SEPARATORETXT + Description; + } + + }//class cNota + +}//namespace A69WD.Data diff --git a/Src/A69WD/Data/cRac.cs b/Src/A69WD/Data/cRac.cs new file mode 100644 index 0000000..c6bb4f1 --- /dev/null +++ b/Src/A69WD/Data/cRac.cs @@ -0,0 +1,830 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace A69WD.Data { + + public class cRac { + + #region Costruttori + + /// + /// Costruttore + /// + public cRac() { isValid = false; } + + /// + /// Costruttore per un racconto nullo, utilizzato per mostrare eventuali errori o messaggi + /// + /// Stringa che si vuole visualizzare come titolo del racconto + /// Stringa che si vuole visualizzare come testo del racconto + public cRac(string title, string trama) { + this.IDrac = 0; + this.Title = title; + this.Trama = "\n\n" + trama + "\n\n"; + this.Creato = DateTime.Now; + this.Updated = DateTime.Now; + this.isValid = true; + } + + + #endregion + + + #region Propietà e Fields: + + /// + /// Identificativo del racconto + /// + public long IDrac = -1; + + /// + /// Titolo del racconto + /// + public string Title = null; + + /// + /// Sottotitolo del racconto + /// + public string SubTitle = null; + + /// + /// Elenco dei tag (ex Props) associati al racconto + /// + public List Tags = null; + + /// + /// Note aggiuntive associate al racconto, sono del tipo: {Key} - {Descrizione} + /// Un tipo di nota sempre presente è la "Src" che individua la sorgente (link del file downloadato) da dove ho preso il racconto + /// Devo poter aver più source e quindi abbandono la struttura dizionario per avere una lista di coppie di stringhe + /// + //public System.Collections.Generic.Dictionary Notes = null; + public List Notes = null; + + /// + /// Elenco degli autori del racconto + /// + public List Autori = null; + + /// + /// Elenco delle origini del racconto + /// + public List Origini = null; + + /// + /// Voto assegnato al racconto + /// + public string Voto = null; + + /// + /// Trama del racconto + /// + public string Trama = null; + + /// + /// Data di creazione/pubblicazione del racconto o in mancanza di essa, data di inserimento del racconto in ATDB + /// + public DateTime Creato = DateTime.MinValue; + + /// + /// Data dell'ultimo update del racconto. + /// Inizialmente sarà la data di inserimento in ATDB, poi sarà la data dell'ultima lettura o dell'ultima iterazione con il racconto stesso. + /// + public DateTime Updated = DateTime.MinValue; + + #endregion + + + #region Metodi: strIDrac, strTags, fullTitle + + /// + /// ID del racconto espresso in formato testuale + /// + public string strIDrac { get { return IDrac.ToString("000000"); } } + + /// + /// Data di creazione del racconto espressa in forma testuale + /// + public string strCreato { get { return DateFormat(Creato); } } + + /// + /// Data di creazione del racconto espressa in forma testuale + /// + public string strUpdated { get { return DateFormat(Updated); } } + + /// + /// Elenco dei tags associati al racconto, espresso come singola stringa in cui i tag sono separati da | + /// + public string strTags { + get { + try { + string msg = ""; + Tags.Sort(); + foreach (string tags in Tags) { + msg += tags + SEPARATORETXT; + } + return msg.Remove(msg.Length - SEPARATORETXT.Length); + } catch { + return " "; + } + } + } + + /// + /// Elenco delle note associate al racconto, espresso come singola stringa in cui ciascuna riga è una nota e utilizzo il separatore per dividere la Key dalla Descrizione + /// + public string strNotes { + get { + try { + string msg = ""; + string endLine = "\r\n"; + Notes.Sort(); + foreach (cNota nota in Notes) { + msg += nota.ToString() + endLine; + } + return msg.Remove(msg.Length - endLine.Length); + } catch { + return " "; + } + } + } + + /// + /// Titolo completo del racconto, cioè il suo titolo con il sottotitolo + /// + public string fullTitle { + get { + if (string.IsNullOrEmpty(SubTitle)) { + return Title; + } else { + return Title + " - " + SubTitle; + } + } + } + + /// + /// Indica se il racconto è valido o no (nullo) + /// + public bool IsValid { get { return isValid; } } + private bool isValid = false; + + /// + /// Esegue la verifica dei dati del racconto e ritorna lo stato di raconto valido. + /// Per ora lo imposta di ufficio a valido, ma in futuro questo è da rivedere. + /// + public bool Validate() { + try { + isValid = true; + if (String.IsNullOrEmpty(Title) || String.IsNullOrWhiteSpace(Title)) { + Logger.Warning("NOT VALIDATE - Missing Title - " + strIDrac + " - " + fullTitle); + isValid = false; + } + if (String.IsNullOrEmpty(Trama) || String.IsNullOrWhiteSpace(Trama)) { + Logger.Warning("NOT VALIDATE - Missing Trama - " + strIDrac + " - " + fullTitle); + isValid = false; + } + if (Autori == null) { + Logger.Warning("NOT VALIDATE - Missing Autors -" + strIDrac + " - " + fullTitle); + isValid = false; + } else { + foreach (string autor in Autori) { + if (String.IsNullOrEmpty(autor) || String.IsNullOrWhiteSpace(autor)) { + Logger.Warning("NOT VALIDATE - Missing Autor -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } + } + if (Tags == null) { + Logger.Warning("NOT VALIDATE - Missing Tags -" + strIDrac + " - " + fullTitle); + isValid = false; + } else { + foreach (string tag in Tags) { + if (String.IsNullOrEmpty(tag) || String.IsNullOrWhiteSpace(tag)) { + Logger.Warning("NOT VALIDATE - Missing Tag -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } + } + if (Creato > Updated) { + Logger.Warning("NOT VALIDATE - Creato > Updated -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } catch (Exception ex) { Logger.Log(new object[] { "Error Code:val001", "Errore in ATWD.Rac.Validate", ex }); } + + try { + //if (!isValid) { + // Logger.Warning("NOT VALIDATE: " + strIDrac + " - " + fullTitle); + //} + } catch (Exception ex) { Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER375278", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); } + + return isValid; + } + + #endregion + + + + /// + /// Crea il file html che rappresenta il racconto. + /// + /// True se tutto ok, False altrimenti. + public bool CreaFileRac() { + bool res = true; + try { + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("\n\t\n\t\t{0}\n\t\t\n\t\n\t\n", fullTitle); + sb.AppendFormat("\t\t

{0}

\n", Title); + if (!string.IsNullOrEmpty(SubTitle)) sb.AppendFormat("\t\t

{0}

\n", SubTitle); + sb.Append("\t\t\n"); + if (Autori.Count == 1) { + sb.AppendFormat("\t\t

Autore: {0}

\n", Autori[0]); + } else { + sb.Append("\t\t

Autore: "); + foreach (string autor in Autori) { + sb.AppendFormat("{0} - ", autor); + } + sb.Append("

\n"); + } + sb.Append("\t\t

Propietà del racconto:
\n"); + foreach (string prop in Tags) { + sb.AppendFormat("{0}
\n", prop); + } + sb.Append("\t\t

"); + sb.AppendFormat("\t\t

Inserito il: {0}

\n", Creato.ToString("dd/MM/yyyy")); + if (Origini.Count == 1) { + sb.AppendFormat("\t\t

Origine: {0}

\n", Origini[0]); + } else { + sb.Append("\t\t

Origine: "); + foreach (string orig in Origini) { + sb.AppendFormat("{0} - ", orig); + } + sb.Append("

\n"); + } + sb.Append("\t\t

Note del racconto:
\n"); + foreach (cNota nota in Notes) { sb.AppendFormat("{0}
\n", nota.ToString()); } + sb.AppendFormat("ID: {0}
\n

", strIDrac); + //sb.AppendFormat("\t\t

{0}

\n", rac.Trama.Replace("\n", "

\n

")); + sb.AppendFormat("\t\t

{0}

\n", Trama.Replace("\n", "
")); + sb.Append("\t\t\n"); + sb.AppendLine("\t\n"); + // Salvo il file + cTools.WriteTextFile(System.IO.Path.Combine(Cfg.Settings.PathDownloadWorking, FileRacName(IDrac)), sb); + } catch (Exception ex) { + Logger.Log(new object[] { "Error Code: eBook003", "Errore in ATWD.frmMain.CreaFileToc(Racs)", ex }); + res = false; + } + return res; + } + + /// + /// Crea il file Markdown che rappresenta un racconto. + /// + /// True se tutto ok, False altrimenti. + public bool CreaFileMD() { + bool res = true; + try { + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("# {0}\n", Title); + if (!string.IsNullOrEmpty(SubTitle)) sb.AppendFormat("## {0}\n", SubTitle); + if (Autori.Count == 1) { + sb.AppendFormat("### By {0}\n", Autori[0]); + } else { + sb.Append("### By "); + foreach (string autor in Autori) { + sb.AppendFormat("{0}, ", autor); + } + sb.Append("\n"); + } + sb.AppendFormat("- Voto: #{0} \n", Voto.Replace(" ", "")); + sb.Append("- Tags: "); + foreach (string prop in Tags) { + sb.AppendFormat("#{0} ", prop.Replace(" ", "")); + } + sb.Append("\n"); + sb.AppendFormat("- Creato: {0}\n", Creato.ToString("dd/MM/yyyy")); + sb.AppendFormat("- Update: {0}\n", Updated.ToString("dd/MM/yyyy")); + if (Origini.Count == 1) { + sb.AppendFormat("- Origin: {0}\n", Origini[0]); + } else { + sb.Append("- Origin: "); + foreach (string orig in Origini) { + sb.AppendFormat(" - {0}\n", orig); + } + } + sb.Append("- Notes: \n"); + foreach (cNota nota in Notes) { sb.AppendFormat(" - {0}
\n", nota.ToString()); } + sb.Append("\n"); + sb.AppendFormat("{0}\n", Trama); + sb.Append("\n"); + sb.Append("\n"); + // Salvo il file + cTools.WriteTextFile(System.IO.Path.Combine(Cfg.Settings.PathDownloadWorking, "Rac" + IDrac.ToString("00000") + ".md"), sb); + } catch (Exception ex) { + Logger.Log(new object[] { "Error Code: eBook003", "Errore in ATWD.frmMain.CreaFileMD(Racs)", ex }); + res = false; + } + return res; + } + + + /// + /// Crea un nome univoco per il file htm che rappresenta un racconto. + /// Rac00000.htm + /// + public static string FileRacName(long RacID) { return "Rac" + RacID.ToString("00000") + ".htm"; } + + /// + /// Stringa di separazione fra i vari campi quando esprimo un elenco tramite una singola stringa + /// + private const string SEPARATORETXT = " -|- "; + + /// + /// Esprime la data indicata con una stringa opportunamente formattata + /// + /// DateTime da esprimere in testo + /// Il testo opportunamente formattato + private string DateFormat(DateTime dt) { return dt.ToString("yyyy/MM/dd"); } + + /// + /// Override per esprimere in modo formale un racconto con una singola stringa. + /// + /// Stringa che rappresenta l'intero racconto + public override string ToString() { + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("- ID Rac:\t{0}\n", strIDrac); + sb.AppendFormat("- Title: \t{0}\n", Title); + sb.AppendFormat("- SubTit:\t{0}\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Autors:\t{0}\n", tmp); + sb.AppendFormat("- Voto: \t{0}\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { tmp += string.Format("{0}{1}", tag, SEPARATORETXT); } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Tags: \t{0}\n", tmp); + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("- Notes: \t{0}{2}{1}\n", nota.Key, nota.Description, SEPARATORETXT); } + } else { sb.Append("- Notes: \n"); } + sb.AppendFormat("- Creato:\t{0}\n", strCreato); + sb.AppendFormat("- Update:\t{0}\n", strUpdated); + tmp = ""; + if (Origini != null) { + Origini.Sort(); + foreach (string origine in Origini) { + tmp += string.Format("{0}{1}", origine, SEPARATORETXT); + } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Origin:\t{0}\n", tmp); + sb.AppendFormat("- Trama: \t{0}\n", Trama); + sb.AppendLine(""); + + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + + } + + /// + /// Esprime il racconto in formato HTML formale. + /// + /// Stringa html che rappresenta l'intero racconto + public string ToHTML() { + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("\n\t\n\t\t{0}\n\t\n\t\n", fullTitle); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

Salta alla fine

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

- ID Rac: {0}

\n", strIDrac); + sb.AppendFormat("\t\t

- Title: {0}

\n", Title); + sb.AppendFormat("\t\t

- SubTit: {0}

\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { tmp += string.Format("{0}{1}", tag, SEPARATORETXT); } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("\t\t

- Notes: {0}{2}{1}

\n", nota.Key, nota.Description, SEPARATORETXT); } + } else { sb.Append("\t\t

- Notes:

\n"); } + sb.AppendFormat("\t\t

- Creato: {0}

\n", strCreato); + sb.AppendFormat("\t\t

- Update: {0}

\n", strUpdated); + sb.AppendFormat("\t\t

- Trama: {0}

\n", Trama.Replace("\n", "\n")); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

Ritorna all'inizio

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendLine("\t\n"); + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + } + + + /// + /// Esprime il racconto in una pagina html con lo style interno. + /// + /// Nome del racconto successivo a cui lincare + /// Stringa html che rappresenta l'intero racconto + public string ToHTML(string NextRacHtmlName) { + //try { + // if (!IsValid) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + // StringBuilder sb = new StringBuilder(); + // sb.AppendFormat("\n\t\n\t\t{0}\n\t\n\t\n", fullTitle); + // sb.AppendLine("\t\t"); + // //sb.AppendFormat("\t\t

Salta alla fine

\n", strIDrac); + // sb.AppendFormat("\t\t

Salta al prossimo

\n", strIDrac); + // sb.AppendLine("\t\t"); + // sb.AppendFormat("\t\t

- ID Rac: {0}

\n", strIDrac); + // sb.AppendFormat("\t\t

- Title: {0}

\n", Title); + // sb.AppendFormat("\t\t

- SubTit: {0}

\n", SubTitle); + // string tmp = ""; + // if (Autori != null) { + // for (int i = 0; i < Autori.Length; i++) { + // tmp += string.Format("{0} | ", Autori[i]); + // } + // if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + // } + // sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + // sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + // tmp = ""; + // if (Tags != null) { + // for (int i = 0; i < Tags.Length; i++) { + // tmp += string.Format("{0} | ", Tags[i]); + // } + // if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + // } + // sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + // tmp = ""; + // if (Notes != null) { + // for (int i = 0; i < Notes.Length; i++) { sb.AppendFormat("\t\t

- {0}

\n", Notes[i]); } + // } else { sb.Append("\t\t

- Notes:

\n"); } + // sb.AppendFormat("\t\t

- Creato: {0}

\n", Creato.ToString("dd/MM/yyyy")); + // sb.AppendFormat("\t\t

- Update: {0}

\n", Updated.ToString("dd/MM/yyyy")); + // sb.AppendFormat("\t\t

- Trama: {0}

\n", Trama.Replace("\n", "\n")); + // sb.AppendLine("\t\t"); + // sb.AppendFormat("\t\t

Ritorna all'inizio

\n", strIDrac); + // sb.AppendLine("\t\t"); + // sb.AppendLine("\t\n"); + // return sb.ToString(); + //} catch (Exception ex) { + // Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + // return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + //} + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.Append("\n\t\n\t\t\n\t\t\n\t\t{0}\n\t\n\t", fullTitle); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t
Salta al prossimo

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

{0}

\n", strIDrac); + sb.AppendFormat("\t\t

{0}

\n", Title); + sb.AppendFormat("\t\t

{0}

\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + } + sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { + tmp += string.Format("{0}{1}", tag, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + } + sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("\t\t

- Notes: {0} - {1}

\n", nota.Key, nota.Description); } + } else { sb.Append("\t\t

- Notes:

\n"); } + sb.AppendFormat("\t\t

- Creato: {0}

\n", strCreato); + sb.AppendFormat("\t\t

- Update: {0}

\n", strUpdated); + sb.AppendFormat("\t\t

{0}

\n", Trama.Replace("\n", "\n")); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t
Ritorna all'inizio

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendLine("\t\n"); + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + } + + + public static int Read(string Txt, out cRac[] Racs) { + + // I racconti inseriti devono avere la struttura formale: + // + // - ID Rac:\t{0}\n + // - Title: \t{0}\n + // - SubTit:\t{0}\n + // - Autors:\t{0}\n Elenco degli autori separati tramite il separatore + // - Voto: \t{0}\n + // - Tags: \t{0}\n Elenco dei tag separati tramite il separatore + // - Notes: \t{0}{2}{1}\n Per ciascuna riga, la coppia Key e Descr separati tramite il separatore + // - Creato:\t{0}\n + // - Update:\t{0}\n + // - Origin:\t{0}\n + // - Trama: \t{0}\n + // + + try { + // Suddivido i vari racconti: + string[] splitSeparator = new string[] { "- ID Rac:" }; + string[] txtRacs = Txt.Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + List elenco = new List(); + // Analizzo ciascuno di essi: + foreach (string txtRac in txtRacs) { + // Leggo il testo riga per riga, fino a che inizia il primo racconto (trovo il tag ID o il titolo): + splitSeparator = new string[] { "\n" }; + string[] rows = ("- ID Rac:" + txtRac).Replace("\r\n", "\n").Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + cRac rac = new cRac(); + int i; + // Ricerco inizio del racconto: + for (i = 0; i < rows.Length; i++) { + if (rows[i].Trim().StartsWith("- ID Rac:")) { + rac.IDrac = long.Parse(rows[i].Replace("- ID Rac:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Title:")) { + rac.Title = rows[i].Replace("- Title:", "").Trim(); + i++; + break; + } + } + if (rows[i].Trim().StartsWith("- SubTit:")) { + rac.SubTitle = rows[i].Replace("- SubTit:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Autors:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] autors = rows[i].Replace("- Autors:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Autori = new List(); + foreach (string aut in autors) { rac.Autori.Add(aut.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Voto:")) { + rac.Voto = rows[i].Replace("- Voto:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Tags:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] tags = rows[i].Replace("- Tags:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Tags = new List(); + foreach (string tag in tags) { rac.Tags.Add(tag.Trim()); } + i++; + } + rac.Notes = new List(); + while (rows[i].Trim().StartsWith("- Notes:")) { + string[] note = rows[i].Replace("- Notes:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + if (note.Length == 2) { rac.Notes.Add(new cNota(note[0].Trim(), note[1].Trim())); } + i++; + } + if (rows[i].Trim().StartsWith("- Creato:")) { + rac.Creato = DateTime.Parse(rows[i].Replace("- Creato:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Update:")) { + rac.Updated = DateTime.Parse(rows[i].Replace("- Update:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Origin:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] origini = rows[i].Replace("- Origin:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Origini = new List(); + foreach (string origine in origini) { rac.Origini.Add(origine.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Trama:")) { + rac.Trama = rows[i].Replace("- Trama:", "").Trim() + "\n"; + i++; + for (int j = i; j < rows.Length; j++) { + rac.Trama += rows[j].Trim() + "\n"; + } + } + if (rac.Validate()) { + elenco.Add(rac); + } else { + Logger.Error("Decodifica del racconto dal testo inserito, non riuscita"); + } + } + + Racs = elenco.ToArray(); + return Racs.Length; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + Racs = null; + return -1; + } + } + + public static int Read_Old(string Txt, out cRac[] Racs) { + + // ToDo: Gestire più racconti in modo da fare una vera e propia importazione + + // I racconti inseriti devono avere la struttura formale: + // + // - ID Rac:\t{0}\n + // - Title: \t{0}\n + // - SubTit:\t{0}\n + // - Autors:\t{0}\n Elenco degli autori separati tramite il separatore + // - Voto: \t{0}\n + // - Tags: \t{0}\n Elenco dei tag separati tramite il separatore + // - Notes: \t{0}{2}{1}\n Per ciascuna riga, la coppia Key e Descr separati tramite il separatore + // - Creato:\t{0}\n + // - Update:\t{0}\n + // - Origin:\t{0}\n + // - Trama: \t{0}\n + // + + try { + // Leggo il testo riga per riga, fino a che inizia il primo racconto (trovo il tag ID o il titolo): + string[] splitSeparator = new string[] { "\n" }; + string[] rows = Txt.Replace("\r\n", "\n").Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + + cRac rac = new cRac(); + int i; + // Ricerco inizio del racconto: + for (i = 0; i < rows.Length; i++) { + if (rows[i].Trim().StartsWith("- ID Rac:")) { + rac.IDrac = long.Parse(rows[i].Replace("- ID Rac:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Title:")) { + rac.Title = rows[i].Replace("- Title:", "").Trim(); + i++; + break; + } + } + if (rows[i].Trim().StartsWith("- SubTit:")) { + rac.SubTitle = rows[i].Replace("- SubTit:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Autors:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] autors = rows[i].Replace("- Autors:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Autori = new List(); + foreach (string aut in autors) { rac.Autori.Add(aut.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Voto:")) { + rac.Voto = rows[i].Replace("- Voto:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Tags:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] tags = rows[i].Replace("- Tags:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Tags = new List(); + foreach (string tag in tags) { rac.Tags.Add(tag.Trim()); } + i++; + } + rac.Notes = new List(); + while (rows[i].Trim().StartsWith("- Notes:")) { + string[] note = rows[i].Replace("- Notes:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + if (note.Length == 2) { rac.Notes.Add(new cNota(note[0].Trim(), note[1].Trim())); } + i++; + } + if (rows[i].Trim().StartsWith("- Creato:")) { + rac.Creato = DateTime.Parse(rows[i].Replace("- Creato:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Update:")) { + rac.Updated = DateTime.Parse(rows[i].Replace("- Update:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Origin:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] origini = rows[i].Replace("- Origin:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Origini = new List(); + foreach (string origine in origini) { rac.Origini.Add(origine.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Trama:")) { + rac.Trama = rows[i].Replace("- Trama:", "").Trim() + "\n"; + i++; + for (int j = i; j < rows.Length; j++) { + rac.Trama += rows[j].Trim() + "\n"; + } + } + Racs = new cRac[1]; + rac.isValid = true; + Racs[0] = rac; + return 1; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + Racs = null; + return -1; + } + } + + public bool UnificaConDuplicato(cRac copia) { + try { + // ID Rac: Tengo l'ID del racconto attuale + // Title: Il titolo è lo stesso e non devo fare nulla + // SubTit: Se è lo stesso tengo l'attuale, altrimenti se uno solo è non nullo lo tengo, altrimenti li unisco. + if (this.SubTitle != copia.SubTitle) { + if (string.IsNullOrEmpty(this.SubTitle)) { + this.SubTitle = copia.SubTitle; + } else { + this.SubTitle = this.SubTitle + SEPARATORETXT + copia.SubTitle; + } + } + // Autors: Unisco tutti gli autori distinti: + foreach (string aut in copia.Autori) { + if (!this.Autori.Contains(aut)) { + this.Autori.Add(aut); + } + } + // Voto: Metto il voto più alto fra i due + if (copia.Voto != this.Voto) if (this.Voto == "Non Letto") this.Voto = copia.Voto; + // Tags: Unisco tutti i tag distinti: + foreach (string tag in copia.Tags) { + if (!this.Tags.Contains(tag)) this.Tags.Add(tag); + } + // Notes: Unisco tutte le note distinte: + foreach (cNota nota in copia.Notes) { + if (!this.Notes.Contains(nota)) this.Notes.Add(nota); + } + // Creato: Uso la data di creazione più vecchia: + if (copia.Creato < this.Creato) this.Creato = copia.Creato; + // Update: Uso la data più nuova + if (copia.Updated > this.Updated) this.Updated = copia.Updated; + // Origin: Unisco tutte le origini distinte: + foreach (string orig in copia.Origini) { + if (!this.Origini.Contains(orig)) this.Origini.Add(orig); + } + // Trama: La trama è la stessa e non devo fare nulla + + return true; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return false; + } + } + + } // class cRac + +}//namespace A69WD.Data